CSS: How to create a background-image masked by a mask-image - css

I have a div that I want to give a regular background-image modified by a mask-image, so that the page background, which uses background-attachment: fixed; can "float" as if seen through a window, behind the div.
For the mask image, I want to be able to use either PNG or SVG.
Even if I use an SVG, I would rather not use the mask:url(mask.svg#element); method because the SVG artwork may not be simple clipping masks, but also include shades of gray in the form of blurs, gradients, etc.
I would like the mask to use the standard white = opaque / black = transparent schema. I believe mask-mode: alpha; is correct for this configuration?
Here's what I've managed to get working so far. The trouble is that it relies on an SVG id (instead of a whole image), and also the size is way smaller than the div, for some reason.
<!DOCTYPE html>
<html>
<head>
<style>
body {
color: #174;
background-color: #def;
font-family: sans-serif;
}
.masked-bg {
width: 600px;
height: 600px;
background:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAL0lEQVQIW22KQQ4AMAjC4P+PZlXnzZoYwVpypFjACsHmCtPlZwxAaCqf5XzWWPsB9TsMBL7veUEAAAAASUVORK5CYII=);
background-repeat: repeat;
background-attachment: fixed;
background-size: 10px;
image-rendering: pixelated;
mask-image: url(#svgmask);
mask-repeat: no-repeat;
mask-size: contain;
mask-position: center;
mask-origin: content-box;
}
</style>
</head>
<body>
<h1>mask-image</h1>
<p>with a fixed background</p>
<div class="masked-bg"></div>
<svg width="0" height="0"> <!-- sized to 0 because this SVG data is only to be used in the div background -->
<mask id="svgmask">
<polygon fill="#ffffff" points="100,10 40,198 190,78 10,78 160,198"></polygon>
<text x="0" y="36" fill="white" transform="rotate(30 20,40)" font-family="sans-serif">V e c t o r</text>
</mask>
</svg>
</body>
</html>

Related

How to make an element of such a complex shape? [duplicate]

So I'm working on a site and I was wondering if it's possible to, purely using HTML5, CSS3 (and JavaScript if needed), make a div with a curved bottom, so it will look practically like this:
Or can this only be done using a background image?
<body>
<div class="navbar navbar-fixed-top">
<div class="navbar-inner">
<ul class="nav">
<li>Home</li>
</ul>
</div>
</div>
</body>
There are different approaches that can be adopted to create this shape. Below is a detailed description of possibilities:
SVG Based Approaches:
SVG is the recommended way to create such shapes. It offers simplicity and scale-ability. Below are a couple of possible ways:
1- Using Path Element:
We can use SVG's path element to create this shape and fill it with some solid color, gradient or a pattern.
Only one attribute d is used to define shapes in path element. This attribute itself contains a number of short commands and few parameters that are necessary for those commands to work.
Below is the necessary code to create this shape:
<path d="M 0,0
L 0,40
Q 250,80 500,40
L 500,0
Z" />
Below is a brief description of path commands used in above code:
M command is used to define the starting point. It appears at the beginning and specify the point from where drawing should start.
L command is used to draw straight lines.
Q command is used to draw curves.
Z command is used to close the current path.
Output Image:
Working Demo:
svg {
width: 100%;
}
<svg width="500" height="80" viewBox="0 0 500 80" preserveAspectRatio="none">
<path d="M0,0 L0,40 Q250,80 500,40 L500,0 Z" fill="black" />
</svg>
2- Clipping:
Clipping means removing or hiding some parts of an element.
In this approach, we define a clipping region by using SVG's clipPath element and apply this to a rectangular element. Any area that is outside the clipping region will be hidden.
Below is the necessary code:
<defs>
<clipPath id="shape">
<path d="M0,0 L0,40 Q250,80 500,40 L500,0 Z" />
</clipPath>
</defs>
<rect x="0" y="0" width="500" height="80" fill="#000" clip-path="url(#shape)" />
Below is brief description of the elements used in above code:
defs element is used to define element / objects for later use in SVG document.
clipPath element is used to define a clipping region.
rect element is used to create rectangles.
clip-path attribute is used to link the clipping path created earlier.
Working Demo:
svg {
width: 100%;
}
<svg width="500" height="80" viewBox="0 0 500 80" preserveAspectRatio="none">
<defs>
<clipPath id="shape">
<path d="M0,0 L0,40 Q250,80 500,40 L500,0 Z" />
</clipPath>
</defs>
<rect x="0" y="0" width="500" height="80" fill="#000" clip-path="url(#shape)" />
</svg>
CSS Based Approaches:
1- Using Pseudo Element:
We can use ::before or ::after pseudo element to create this shape. Steps to create this are given below:
Create a layer with ::before OR ::after pseudo element having width and height more than its parent.
Add border-radius to create the rounded shape.
Add overflow: hidden on parent to hide the unnecessary part.
Required HTML:
All we need is a single div element possibly having some class like shape:
<div class="shape"></div>
Working Demo:
.shape {
position: relative;
overflow: hidden;
height: 80px;
}
.shape::before {
border-radius: 100%;
position: absolute;
background: black;
right: -200px;
left: -200px;
top: -200px;
content: '';
bottom: 0;
}
<div class="shape"></div>
2- Radial Gradient:
In this approach we will use CSS3's radial-gradient() function to draw this shape on the element as a background. However, this approach doesn't produce very sharp image and it might have some jagged corners.
Required HTML:
Only single div element with some class will be required i.e.
<div class="shape"></div>
Necessary CSS:
.shape {
background-image: radial-gradient(120% 120px at 50% -30px, #000 75%, transparent 75%);
}
Working Demo:
.shape {
background: radial-gradient(120% 120px at 50% -30px, #000 75%, transparent 75%) no-repeat;
height: 80px;
}
<div class="shape"></div>
JavaScript Based Approaches:
Although not required in this case but for the sake of completeness, I'm adding this approach as well. This can be useful in some cases as well:
HTML5 Canvas:
We can draw this shape on HTML5 Canvas element using path functions:
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(0, 40);
ctx.quadraticCurveTo(311, 80, 622, 40);
ctx.lineTo(622, 0);
ctx.fill();
<canvas id="canvas" width="622" height="80"></canvas>
Below is a brief description of the methods used in above code:
beginPath() is used to create a new path. Once a new path is created, future drawing commands are directed into the path.
moveTo(x, y) moves the pen to the coordinates specified by x and y.
lineTo(x, y) draws a straight line from the current pen position to the point specified by x and y.
quadraticCurveTo(cp1x, cp1y, x, y) draws a curve from current pen position to the point specified by x and y using control point specified by cp1x and cp1y.
fill() fills the current path using non-zero or even-odd winding rule.
Useful Resources:
Radial Gradient: Specs, MDN
SVG: Specs, MDN
HTML5 Canvas: Specs, MDN
CSS:
div{
background-color:black;
width:500px;
height:50px;
border-bottom-left-radius:50%;
border-bottom-right-radius:50%;
}
see is this ok for you
div {
background-color: black;
width: 500px;
height: 50px;
border-bottom-left-radius: 50%;
border-bottom-right-radius: 50%;
}
<div>
</div>
This is what you want:
div{
background-color: black;
width: 500px;
height: 300px;
border-radius: 0 0 50% 50% / 50px;
}
Unlike the accepted answer, this works even when the height of the div is increased.
Demo: jsFiddle
Yes, you can do this in CSS - basically make your div wider than the page to fix the too-rounded edges, then left-positioned to compensate, with bottom border radius using both x & y values, and negative bottom margin to compensate for the gap:
.round-bottom {
border-bottom-left-radius: 50% 200px; // across half & up 200px at left edge
border-bottom-right-radius: 50% 200px; // across half & up 200px at right edge
width: 160%; overflow: hidden; // make larger, hide side bits
margin-bottom: -50px; // apply negative margin to compensate for bottom gap
position: relative; left:-30%; // re-position whole element so extra is on each side (you may need to add display:block;)
}
.round-bottom {
border-bottom-left-radius: 50% 150px !important;
border-bottom-right-radius: 50% 150px !important;
position: relative;
overflow: hidden;
width: 160%;
margin-bottom:-50px;
left:-30%;
background-color:#444;
background-image: url('https://upload.wikimedia.org/wikipedia/commons/a/a2/Tropical_Forest_with_Monkeys_A10893.jpg'); background-position: center center;
background-size: 42% auto;
height:150px;
}
.container { width: 100%; height: height:100px; padding-bottom:50px; overflow:hidden;}
<div class="container"><div class="round-bottom"></div></div>
Try this
.navbar{
border-radius:50% 50% 0 0;
-webkit-border-radius:50% 50% 0 0;
background:#000;
min-height:100px;
}
jsFiddle File

Modify SVG colors using CSS variables [duplicate]

Placing the SVG output directly inline with the page code I am able to simply modify fill colors with CSS like so:
polygon.mystar {
fill: blue;
}​
circle.mycircle {
fill: green;
}
This works great, however I'm looking for a way to modify the "fill" attribute of an SVG when it's being served as a BACKGROUND-IMAGE.
html {
background-image: url(../img/bg.svg);
}
How can I change the colors now? Is it even possible?
For reference, here are the contents of my external SVG file:
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
width="320px" height="100px" viewBox="0 0 320 100" enable-background="new 0 0 320 100" xml:space="preserve">
<polygon class="mystar" fill="#3CB54A" points="134.973,14.204 143.295,31.066 161.903,33.77 148.438,46.896 151.617,65.43 134.973,56.679
118.329,65.43 121.507,46.896 108.042,33.77 126.65,31.066 "/>
<circle class="mycircle" fill="#ED1F24" cx="202.028" cy="58.342" r="12.26"/>
</svg>
You can use CSS masks, With the 'mask' property, you create a mask that is applied to an element.
.icon {
background-color: red;
-webkit-mask-image: url(icon.svg);
mask-image: url(icon.svg);
}
For more see this great article: https://codepen.io/noahblon/post/coloring-svgs-in-css-background-images
I needed something similar and wanted to stick with CSS. Here are LESS and SCSS mixins as well as plain CSS that can help you with this. Unfortunately, it's browser support is a bit lax. See below for details on browser support.
LESS mixin:
.element-color(#color) {
background-image: url('data:image/svg+xml;utf8,<svg ...><g stroke="#{color}" ... /></g></svg>');
}
LESS usage:
.element-color(#fff);
SCSS mixin:
#mixin element-color($color) {
background-image: url('data:image/svg+xml;utf8,<svg ...><g stroke="#{$color}" ... /></g></svg>');
}
SCSS usage:
#include element-color(#fff);
CSS:
// color: red
background-image: url('data:image/svg+xml;utf8,<svg ...><g stroke="red" ... /></g></svg>');
Here is more info on embedding the full SVG code into your CSS file. It also mentioned browser compatibility which is a bit too small for this to be a viable option.
One way to do this is to serve your svg from some server side mechanism.
Simply create a resource server side that outputs your svg according to GET parameters, and you serve it on a certain url.
Then you just use that url in your css.
Because as a background img, it isn't part of the DOM and you can't manipulate it.
Another possibility would be to use it regularly, embed it in a page in a normal way, but position it absolutely, make it full width & height of a page and then use z-index css property to put it behind all the other DOM elements on a page.
Yet another approach is to use mask. You then change the background color of the masked element. This has the same effect as changing the fill attribute of the svg.
HTML:
<glyph class="star"/>
<glyph class="heart" />
<glyph class="heart" style="background-color: green"/>
<glyph class="heart" style="background-color: blue"/>
CSS:
glyph {
display: inline-block;
width: 24px;
height: 24px;
}
glyph.star {
-webkit-mask: url(star.svg) no-repeat 100% 100%;
mask: url(star.svg) no-repeat 100% 100%;
-webkit-mask-size: cover;
mask-size: cover;
background-color: yellow;
}
glyph.heart {
-webkit-mask: url(heart.svg) no-repeat 100% 100%;
mask: url(heart.svg) no-repeat 100% 100%;
-webkit-mask-size: cover;
mask-size: cover;
background-color: red;
}
You will find a full tutorial here: http://codepen.io/noahblon/blog/coloring-svgs-in-css-background-images (not my own). It proposes a variety of approaches (not limited to mask).
Use the sepia filter along with hue-rotate, brightness, and saturation to create any color we want.
.colorize-pink {
filter: brightness(0.5) sepia(1) hue-rotate(-70deg) saturate(5);
}
https://css-tricks.com/solved-with-css-colorizing-svg-backgrounds/
It's possible with Sass!
The only thing you have to do is to url-encode your svg code. And this is possible with a helper function in Sass. I've made a codepen for this. Look at this:
http://codepen.io/philippkuehn/pen/zGEjxB
// choose a color
$icon-color: #F84830;
// functions to urlencode the svg string
#function str-replace($string, $search, $replace: '') {
$index: str-index($string, $search);
#if $index {
#return str-slice($string, 1, $index - 1) + $replace + str-replace(str-slice($string, $index + str-length($search)), $search, $replace);
}
#return $string;
}
#function url-encode($string) {
$map: (
"%": "%25",
"<": "%3C",
">": "%3E",
" ": "%20",
"!": "%21",
"*": "%2A",
"'": "%27",
'"': "%22",
"(": "%28",
")": "%29",
";": "%3B",
":": "%3A",
"#": "%40",
"&": "%26",
"=": "%3D",
"+": "%2B",
"$": "%24",
",": "%2C",
"/": "%2F",
"?": "%3F",
"#": "%23",
"[": "%5B",
"]": "%5D"
);
$new: $string;
#each $search, $replace in $map {
$new: str-replace($new, $search, $replace);
}
#return $new;
}
#function inline-svg($string) {
#return url('data:image/svg+xml;utf8,#{url-encode($string)}');
}
// icon styles
// note the fill="' + $icon-color + '"
.icon {
display: inline-block;
width: 50px;
height: 50px;
background: inline-svg('<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
viewBox="0 0 30 30" enable-background="new 0 0 30 30" xml:space="preserve">
<path fill="' + $icon-color + '" d="M18.7,10.1c-0.6,0.7-1,1.6-0.9,2.6c0,0.7-0.6,0.8-0.9,0.3c-1.1-2.1-0.4-5.1,0.7-7.2c0.2-0.4,0-0.8-0.5-0.7
c-5.8,0.8-9,6.4-6.4,12c0.1,0.3-0.2,0.6-0.5,0.5c-0.6-0.3-1.1-0.7-1.6-1.3c-0.2-0.3-0.4-0.5-0.6-0.8c-0.2-0.4-0.7-0.3-0.8,0.3
c-0.5,2.5,0.3,5.3,2.1,7.1c4.4,4.5,13.9,1.7,13.4-5.1c-0.2-2.9-3.2-4.2-3.3-7.1C19.6,10,19.1,9.6,18.7,10.1z"/>
</svg>');
}
.icon {
width: 48px;
height: 48px;
display: inline-block;
background: url(https://s3-us-west-2.amazonaws.com/s.cdpn.io/18515/heart.svg) no-repeat 50% 50%;
background-size: cover;
}
.icon-orange {
-webkit-filter: hue-rotate(40deg) saturate(0.5) brightness(390%) saturate(4);
filter: hue-rotate(40deg) saturate(0.5) brightness(390%) saturate(4);
}
.icon-yellow {
-webkit-filter: hue-rotate(70deg) saturate(100);
filter: hue-rotate(70deg) saturate(100);
}
codeben article and demo
Now you can achieve this on the client side like this:
var green = '3CB54A';
var red = 'ED1F24';
var svg = '<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="320px" height="100px" viewBox="0 0 320 100" enable-background="new 0 0 320 100" xml:space="preserve"> <polygon class="mystar" fill="#'+green+'" points="134.973,14.204 143.295,31.066 161.903,33.77 148.438,46.896 151.617,65.43 134.973,56.679 118.329,65.43 121.507,46.896 108.042,33.77 126.65,31.066 "/><circle class="mycircle" fill="#'+red+'" cx="202.028" cy="58.342" r="12.26"/></svg>';
var encoded = window.btoa(svg);
document.body.style.background = "url(data:image/svg+xml;base64,"+encoded+")";
Fiddle here!
Download your svg as text.
Modify your svg text using javascript to change the paint/stroke/fill color[s].
Then embed the modified svg string inline into your css as described here.
If you are trying to use and SVG directly on CSS with url() like this;
a:before {
content: url('data:image/svg+xml; utf8, <svg xmlns="http://www.w3.org/2000/svg" x="0" y="0" viewBox="0 0 451 451"><path d="M345.441,2...
You should encode the # to %23, otherwise it won't work.
<svg fill="%23FFF" ...
You can store the SVG in a variable. Then manipulate the SVG string depending on your needs (i.e., set width, height, color, etc). Then use the result to set the background, e.g.
$circle-icon-svg: '<svg xmlns="http://www.w3.org/2000/svg"><circle cx="10" cy="10" r="10" /></svg>';
$icon-color: #f00;
$icon-color-hover: #00f;
#function str-replace($string, $search, $replace: '') {
$index: str-index($string, $search);
#if $index {
#return str-slice($string, 1, $index - 1) + $replace + str-replace(str-slice($string, $index + str-length($search)), $search, $replace);
}
#return $string;
}
#function svg-fill ($svg, $color) {
#return str-replace($svg, '<svg', '<svg fill="#{$color}"');
}
#function svg-size ($svg, $width, $height) {
$svg: str-replace($svg, '<svg', '<svg width="#{$width}"');
$svg: str-replace($svg, '<svg', '<svg height="#{$height}"');
#return $svg;
}
.icon {
$icon-svg: svg-size($circle-icon-svg, 20, 20);
width: 20px; height: 20px; background: url('data:image/svg+xml;utf8,#{svg-fill($icon-svg, $icon-color)}');
&:hover {
background: url('data:image/svg+xml;utf8,#{svg-fill($icon-svg, $icon-color-hover)}');
}
}
I have made a demo too, http://sassmeister.com/gist/4cf0265c5d0143a9e734.
This code makes a few assumptions about the SVG, e.g. that <svg /> element does not have an existing fill colour and that neither width or height properties are set. Since the input is hardcoded in the SCSS document, it is quite easy to enforce these constraints.
Do not worry about the code duplication. gzip compression makes the difference negligible.
You can use the brightness filter, any value greater than 1 makes the element brighter, and any value less than 1 makes it darker. So, we can make those light SVG’s dark, and vice versa, for example, this will make the svg darker:
filter: brightness(0);
In order to change the color and not only brightness level we can use sepia filter along with hue-rotate, brightness, for example:
.colorize-blue {
filter: brightness(0.5) sepia(1) hue-rotate(140deg) saturate(6);
}
You can create your own SCSS function for this. Adding the following to your config.rb file.
require 'sass'
require 'cgi'
module Sass::Script::Functions
def inline_svg_image(path, fill)
real_path = File.join(Compass.configuration.images_path, path.value)
svg = data(real_path)
svg.gsub! '{color}', fill.value
encoded_svg = CGI::escape(svg).gsub('+', '%20')
data_url = "url('data:image/svg+xml;charset=utf-8," + encoded_svg + "')"
Sass::Script::String.new(data_url)
end
private
def data(real_path)
if File.readable?(real_path)
File.open(real_path, "rb") {|io| io.read}
else
raise Compass::Error, "File not found or cannot be read: #{real_path}"
end
end
end
Then you can use it in your CSS:
.icon {
background-image: inline-svg-image('icons/icon.svg', '#555');
}
You will need to edit your SVG files and replace any fill attributes in the markup with fill="{color}"
The icon path is always relative to your images_dir parameter in the same config.rb file.
Similar to some of the other solutions, but this is pretty clean and keeps your SCSS files tidy!
In some (very specific) situations this might be achieved by using a filter. For example, you can change a blue SVG image to purple by rotating the hue 45 degrees using filter: hue-rotate(45deg);. Browser support is minimal but it's still an interesting technique.
Demo
If you wanna swap in a simple way from white to black or some like that, try this:
filter: invert(100%);
for monochrome background you could use a svg with a mask, where the background color should be displayed
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" preserveAspectRatio="xMidYMid meet" focusable="false" style="pointer-events: none; display: block; width: 100%; height: 100%;" >
<defs>
<mask id="Mask">
<rect width="100%" height="100%" fill="#fff" />
<polyline stroke-width="2.5" stroke="black" stroke-linecap="square" fill="none" transform="translate(10.373882, 8.762969) rotate(-315.000000) translate(-10.373882, -8.762969) " points="7.99893906 13.9878427 12.7488243 13.9878427 12.7488243 3.53809523"></polyline>
</mask>
</defs>
<rect x="0" y="0" width="20" height="20" fill="white" mask="url(#Mask)" />
</svg>
and than use this css
background-repeat: no-repeat;
background-position: center center;
background-size: contain;
background-image: url(your/path/to.svg);
background-color: var(--color);
Since this comes up on Google despite the age, I thought I might as well give a solution that I'm employing in the distant future of 2022 after looking at the options here.
This is really just the mask solution from before, but on a pseudo-element.
.icon {
height: 1.5rem;
width: 1.5rem;
}
.icon::before {
content: "";
display: block;
width: 100%;
height: 100%;
mask-repeat: no-repeat;
mask-position: center;
mask-size: contain;
mask-image: url("path/to/svg/icon.svg");
-webkit-mask-repeat: no-repeat;
-webkit-mask-position: center;
-webkit-mask-size: contain;
-webkit-mask-image: url("path/to/svg/icon.svg");
}
This works in all major browsers today, although obviously you can't have an SVG with multiple colors using this. That's the cost of business if the site doesn't let you inject them inline, or if you don't fancy doing font icons, etc.
Late to the show here, BUT, I was able to add a fill color to the SVG polygon, if you're able to directly edit the SVG code, so for example the following svg renders red, instead of default black. I have not tested outside of Chrome though:
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
width="500px" height="500px" viewBox="0 0 500 500" enable-background="new 0 0 500 500" xml:space="preserve">
<polygon
fill="red"
fill-rule="evenodd" clip-rule="evenodd" points="452.5,233.85 452.5,264.55 110.15,264.2 250.05,390.3 229.3,413.35
47.5,250.7 229.3,86.7 250.05,109.75 112.5,233.5 "/>
</svg>
The only way i found for this, and to be cross browser (aka bulletproof), is to render the SVG with PHP and pass Query String to set the color.
The SVG, here called "arrow.php"
<?php
$fill = filter_input(INPUT_GET, 'fill');
$fill = strtolower($fill);
$fill = preg_replace("/[^a-z0-9]/", '', $fill);
if(empty($fill)) $fill = "000000";
header('Content-type: image/svg+xml');
echo '<?xml version="1.0" encoding="utf-8"?>';
?>
<svg xmlns="http://www.w3.org/2000/svg" width="7.4" height="12" viewBox="0 0 7.4 12">
<g>
<path d="M8.6,7.4,10,6l6,6-6,6L8.6,16.6,13.2,12Z" transform="translate(-8.6 -6)" fill="#<?php echo htmlspecialchars($fill); ?>" fill-rule="evenodd"/>
</g>
</svg>
Then you call the image like this
.cssclass{ background-image: url(arrow.php?fill=112233); }
Works only with PHP. And remember that everytime you change the color value, your browser will load a new image.
scss create function
#function url-svg($icon) {
#return url("data:image/svg+xml;utf8,#{str-replace($icon, "#", "%23")}");
}
scss use
url-svg('<svg width="15" height="15" viewBox="0 0 15 15" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M13.125 0H1.875C0.84082 0 0 0.84082 0 1.875V10.3125C0 11.3467 0.84082 12.1875 1.875 12.1875H4.6875V14.6484C4.6875 14.9355 5.01563 15.1025 5.24707 14.9326L8.90625 12.1875H13.125C14.1592 12.1875 15 11.3467 15 10.3125V1.875C15 0.84082 14.1592 0 13.125 0Z" fill="#8A8A8F"/></svg>')
css generated
url('data:image/svg+xml;utf8,<svg width="15" height="15" viewBox="0 0 15 15" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M13.125 0H1.875C0.84082 0 0 0.84082 0 1.875V10.3125C0 11.3467 0.84082 12.1875 1.875 12.1875H4.6875V14.6484C4.6875 14.9355 5.01563 15.1025 5.24707 14.9326L8.90625 12.1875H13.125C14.1592 12.1875 15 11.3467 15 10.3125V1.875C15 0.84082 14.1592 0 13.125 0Z" fill="%238A8A8F"/></svg>')
The str-replace function is used from bootstrap.
Here is another solution using a gradient and a monochrome icon as background and background-blend-mode to colorize the icon.
It requires the background-color to be white, else the whole background gets colored. I only tested on Chrome.
.colored-background {
background-image: linear-gradient(45deg, green, green), url('data:image/svg+xml;charset=US-ASCII,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%22292.4%22%20height%3D%22292.4%22%3E%3Cpath%20fill%3D%22%23000000%22%20d%3D%22M287%2069.4a17.6%2017.6%200%200%200-13-5.4H18.4c-5%200-9.3%201.8-12.9%205.4A17.6%2017.6%200%200%200%200%2082.2c0%205%201.8%209.3%205.4%2012.9l128%20127.9c3.6%203.6%207.8%205.4%2012.8%205.4s9.2-1.8%2012.8-5.4L287%2095c3.5-3.5%205.4-7.8%205.4-12.8%200-5-1.9-9.2-5.5-12.8z%22%2F%3E%3C%2Fsvg%3E');
background-color: #fff;
background-blend-mode: lighten, normal;
background-repeat: no-repeat;
background-position: center, center right .8em;
background-size: auto, 0.6em;
color: red;
display: inline-flex;
align-items: center;
padding: 0.5em;
padding-right: 2em;
height: 1.6em;
width: auto;
border: 1px solid gray;
}
.bg {
background-color: #ddd;
padding: 1em;
}
<div class="bg">
<div class="colored-background">green icon from black svg</div>
</div>
Related to a closed question that is linked to here, but not related directly to this question.
So in case, anyone needs actually to replace src like in the linked question, there is already an answer there. Furthermore if anyone is coming from Vue, and the src path is change on compile, I've come up with a different solution.
In my case, the parent element is a link, but it could be anything really.
<a
v-for="document in documents" :key="document.uuid"
:href="document.url"
target="_blank"
class="item flex align-items-center gap-2 hover-parent"
>
<img alt="documents" class="icon" src="../assets/PDF.svg" />
<strong>{{ document.name }}</strong>
<img class="itemImage ml-auto hide-on-parent-hover" src="../assets/download-circular-button.svg" />
<img class="itemImage ml-auto show-on-parent-hover" src="../assets/download-circular-button-hover.svg" />
</a>
.hover-parent .show-on-parent-hover { display: none }
.hover-parent .hide-on-parent-hover { display: block }
.hover-parent:hover .show-on-parent-hover { display: block }
.hover-parent:hover .hide-on-parent-hover { display: none }
So the solution here is not to change src attribute, but instead to put both <img> elements in the DOM and only display the one that is needed.
If you don't have a parent element that's supposed to be hovered on, you can simply wrap both images in a div.
<div class="hover-parent" >
<img class="hide-on-parent-hover" src="../assets/download-circular-button.svg" />
<img class="show-on-parent-hover" src="../assets/download-circular-button-hover.svg" />
</div>
You might also change CSS to the following, so the .hover-parent ancestor must be a direct parent:
.hover-parent > .show-on-parent-hover { display: none }
.hover-parent > .hide-on-parent-hover { display: block }
.hover-parent:hover > .show-on-parent-hover { display: block }
.hover-parent:hover > .hide-on-parent-hover { display: none }
This is my favorite method, but your browser support must be very progressive. With the mask property you create a mask that is applied to an element. Everywhere the mask is opaque, or solid, the underlying image shows through. Where it’s transparent, the underlying image is masked out, or hidden. The syntax for a CSS mask-image is similar to background-image.look at the codepenmask
A lot of IFs, but if your pre base64 encoded SVG starts:
<svg fill="#000000
Then the base64 encoded string will start:
PHN2ZyBmaWxsPSIjMDAwMDAw
if the pre-encoded string starts:
<svg fill="#bfa76e
then this encodes to:
PHN2ZyBmaWxsPSIjYmZhNzZl
Both encoded strings start the same:
PHN2ZyBmaWxsPSIj
The quirk of base64 encoding is every 3 input characters become 4 output characters. With the SVG starting like this then the 6-character hex fill color starts exactly on an encoding block 'boundary'.
Therefore you can easily do a cross-browser JS replace:
output = input.replace(/MDAwMDAw/, "YmZhNzZl");
But tnt-rox answer above is the way to go moving forward.

IE and Edge ignore absolute position of svg [duplicate]

I decided to switch to svg symbols for one of my projects - but need them to be responsive. The main idea is not to have multiple http requests, so I was thinking of merging all SVGs into one SVG, define symbols and use them as follows:
<svg style="display:none;">
<defs>
<symbol id="mys">
<path fill-rule="evenodd" clip-rule="evenodd" fill="#3F77BC" d="M222.1,77.7h-10.3c0.1-0.8,0.2-1.4,0.2-2.3
c0-8.5-6.9-15.4-15.4-15.4c-8.5,0-15.4,6.9-15.4,15.4c0,0.9,0.1,1.5,0.2,2.3h-9.3v4h-24.9v-5.2H89.4c0-0.3,0-0.6,0-0.9
C89.4,67.1,82.5,60,74,60s-15.4,6.9-15.4,15.4c0,0.3,0,0.6,0,0.9h-6.2V60.7h4.3l5.3-5.3h22.8L74.3,44.9l-13.5-3.6l0.5-1.7
l-16.5-4.4c-0.3,0.1-0.7,0.2-1,0.2l0,21.4h2v7.2c0,0-2,0.6-1.9,1.3c0.1,0.7,4.1,2.6,3.4,5.5c-0.6,2.9-1.6,4.8-4.4,4.5
c-2.7-0.3-3.4-1.4-3.4-2.6c-0.1-1.2,0-3,0-3L38,67.9c0,0,2-0.5,2.6,1.1c0.6,1.5-0.2,2.7,0.6,3.5c0.8,0.8,4.1,1.4,4.1-1.1
c0-2.5-0.5-2.4-2.1-3.6c-1.7-1.2-3.4-2.8-3.4-3.3c0-0.5-0.1-7.7-0.1-7.7h2.1l0-21.7c-1.4-0.7-2.5-2.1-2.5-3.8
c0-2.3,1.9-4.2,4.2-4.2c2,0,3.6,1.4,4.1,3.2l15.3,4.1l0.4-1.6l55.8,15.1h28.1c0,0,0-23.5,0-26.2c0-2.7,2.1-2.6,2.1-2.6
s32.5-0.5,35.1,0.5c2.7,1,3.3,3.7,3.3,3.7h-2l5,11.6c0,0,7.3,4.6,17.6,7.6c10.3,3,13.6,7.6,13.6,7.6l-1,17.6l1.3,2V77.7z
M81.5,46.8l8.6,8.6h9.3l2.9-2.9L81.5,46.8z M175.5,25l-17.4-0.1v12.6h9.6l2.7,2.7h6.6L175.5,25z M183,23.7h-4c0,0,2,6.6,3,9.9
s0.9,4.2,2.7,4.2c1.9,0,4.2,0,4.2,0L183,23.7z M74.2,63.8c6.8,0,12.3,5.5,12.3,12.3S81,88.4,74.2,88.4c-6.8,0-12.3-5.5-12.3-12.3
S67.4,63.8,74.2,63.8z M196.6,63.8c6.8,0,12.3,5.5,12.3,12.3s-5.5,12.3-12.3,12.3s-12.3-5.5-12.3-12.3S189.8,63.8,196.6,63.8z"/>
</symbol>
</defs>
</svg>
<div style="position:relative;width:100%;background:blue;">
<svg class="mys" viewBox="0 0 254 108" preserveAspectRatio="xMaxYMax meet" style="width:100%;">
<use xlink:href="#mys"></use>
<svg>
</div>
Here is a jsfiddle, check the different behaviour in IE (I checked 11 but read that 9 has multiple issues as well):
http://jsfiddle.net/ws472q71/
For the life of me I can't get this to work properly. The above code works correctly in Firefox and Chrome, but fails in IE. I read about IE issues, but I couldn't find anything that works.
What am I doing wrong?
Is there any other similar solution that can merge SVGs into one file and use them as responsive images?
Thanks!
As you have discovered, IE has a bug where it doesn't scale the SVG properly if you don't provide both the width and height.
To get it working in IE, you can use a trick discovered (?) by Nicolas Gallagher.
http://nicolasgallagher.com/canvas-fix-svg-scaling-in-internet-explorer/
The trick uses a <canvas> element. IE does properly scale canvas elements. So if you place one in the <div> with the SVG, the SVG will end up the correct size. You just need to give the canvas the same aspect ratio as your SVG.
<div style="position:relative;width:100%;background:blue;">
<canvas width="254" height="108"></canvas>
<svg class="mys" viewBox="0 0 254 108" preserveAspectRatio="xMaxYMax meet">
<use xlink:href="#mys"></use>
</svg>
</div>
with CSS
canvas {
display: block;
width: 100%;
visibility: hidden;
}
svg {
position: absolute;
top: 0;
left: 0;
width: 100%;
}
canvas {
display: block;
width: 100%;
visibility: hidden;
}
svg {
position: absolute;
top: 0;
left: 0;
width: 100%;
}
<svg style="display:none;">
<defs>
<symbol id="mys">
<path fill-rule="evenodd" clip-rule="evenodd" fill="#3F77BC" d="M222.1,77.7h-10.3c0.1-0.8,0.2-1.4,0.2-2.3
c0-8.5-6.9-15.4-15.4-15.4c-8.5,0-15.4,6.9-15.4,15.4c0,0.9,0.1,1.5,0.2,2.3h-9.3v4h-24.9v-5.2H89.4c0-0.3,0-0.6,0-0.9
C89.4,67.1,82.5,60,74,60s-15.4,6.9-15.4,15.4c0,0.3,0,0.6,0,0.9h-6.2V60.7h4.3l5.3-5.3h22.8L74.3,44.9l-13.5-3.6l0.5-1.7
l-16.5-4.4c-0.3,0.1-0.7,0.2-1,0.2l0,21.4h2v7.2c0,0-2,0.6-1.9,1.3c0.1,0.7,4.1,2.6,3.4,5.5c-0.6,2.9-1.6,4.8-4.4,4.5
c-2.7-0.3-3.4-1.4-3.4-2.6c-0.1-1.2,0-3,0-3L38,67.9c0,0,2-0.5,2.6,1.1c0.6,1.5-0.2,2.7,0.6,3.5c0.8,0.8,4.1,1.4,4.1-1.1
c0-2.5-0.5-2.4-2.1-3.6c-1.7-1.2-3.4-2.8-3.4-3.3c0-0.5-0.1-7.7-0.1-7.7h2.1l0-21.7c-1.4-0.7-2.5-2.1-2.5-3.8
c0-2.3,1.9-4.2,4.2-4.2c2,0,3.6,1.4,4.1,3.2l15.3,4.1l0.4-1.6l55.8,15.1h28.1c0,0,0-23.5,0-26.2c0-2.7,2.1-2.6,2.1-2.6
s32.5-0.5,35.1,0.5c2.7,1,3.3,3.7,3.3,3.7h-2l5,11.6c0,0,7.3,4.6,17.6,7.6c10.3,3,13.6,7.6,13.6,7.6l-1,17.6l1.3,2V77.7z
M81.5,46.8l8.6,8.6h9.3l2.9-2.9L81.5,46.8z M175.5,25l-17.4-0.1v12.6h9.6l2.7,2.7h6.6L175.5,25z M183,23.7h-4c0,0,2,6.6,3,9.9
s0.9,4.2,2.7,4.2c1.9,0,4.2,0,4.2,0L183,23.7z M74.2,63.8c6.8,0,12.3,5.5,12.3,12.3S81,88.4,74.2,88.4c-6.8,0-12.3-5.5-12.3-12.3
S67.4,63.8,74.2,63.8z M196.6,63.8c6.8,0,12.3,5.5,12.3,12.3s-5.5,12.3-12.3,12.3s-12.3-5.5-12.3-12.3S189.8,63.8,196.6,63.8z"/>
</symbol>
</defs>
</svg>
<div style="position:relative;width:100%;background:blue;">
<canvas width="254" height="108"></canvas>
<svg class="mys" viewBox="0 0 254 108" preserveAspectRatio="xMaxYMax meet">
<use xlink:href="#mys"></use>
</svg>
</div>
The trick works whether you are trying to get it to match a width or a height.
On a side note to help anyone struggling to implement this fix or finding its not working with external svg files rather than in-page svg markup
You need to ensure that when editing your svg file in a text editor it is not missing viewBox or preserveAspectRatio attributes in the opening <svg> tag. If these are missing regardless of what fixes you apply the svg will still not scale in IE - even though it'll scale in other browsers without issue.
If these options are set you can define the width/height on the image element used to pull in the svg to 100% and use max-width or max-height to limit the scaling and it will perform as expected. Though - you could still get some alignment issues.
Nicolas Gallagher's solution works great, however, I ran into some responsive issues as I decreased the viewport. I thought I would pass along the fix I used:
<div class="parent-div">
<canvas width="3" height="1"></canvas>
<svg class="mys" viewBox="0 0 254 108">
<use xlink:href="#mys"></use>
</svg>
</div>
I updated the "parent-div" with max-width:100%;
.parent-div{
position: relative;
display: inline-block;
height: 550px;
max-width: 100%;
}
This will not solve all your scaling issues. You will still have to use media queries to change the height as you go, but at least the svg doesn't blow out its container. Hope this helps someone.
This can be rewritten like so if you're working with <img>
HTML
<div class="ie-svgHeight">
<img src="path.svg" class="ie-svgHeight-img">
<canvas class="ie-svgHeight-canvas"></canvas>
</div>
SCSS
.ie-svgHeight {
position: relative;
&-canvas {
display: block;
visibility: hidden;
position: absolute;
top: 0;
left: 0;
height: 100%;
}
&-img { height: 100%; }
}

SVG fill in CSS? [duplicate]

Placing the SVG output directly inline with the page code I am able to simply modify fill colors with CSS like so:
polygon.mystar {
fill: blue;
}​
circle.mycircle {
fill: green;
}
This works great, however I'm looking for a way to modify the "fill" attribute of an SVG when it's being served as a BACKGROUND-IMAGE.
html {
background-image: url(../img/bg.svg);
}
How can I change the colors now? Is it even possible?
For reference, here are the contents of my external SVG file:
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
width="320px" height="100px" viewBox="0 0 320 100" enable-background="new 0 0 320 100" xml:space="preserve">
<polygon class="mystar" fill="#3CB54A" points="134.973,14.204 143.295,31.066 161.903,33.77 148.438,46.896 151.617,65.43 134.973,56.679
118.329,65.43 121.507,46.896 108.042,33.77 126.65,31.066 "/>
<circle class="mycircle" fill="#ED1F24" cx="202.028" cy="58.342" r="12.26"/>
</svg>
You can use CSS masks, With the 'mask' property, you create a mask that is applied to an element.
.icon {
background-color: red;
-webkit-mask-image: url(icon.svg);
mask-image: url(icon.svg);
}
For more see this great article: https://codepen.io/noahblon/post/coloring-svgs-in-css-background-images
I needed something similar and wanted to stick with CSS. Here are LESS and SCSS mixins as well as plain CSS that can help you with this. Unfortunately, it's browser support is a bit lax. See below for details on browser support.
LESS mixin:
.element-color(#color) {
background-image: url('data:image/svg+xml;utf8,<svg ...><g stroke="#{color}" ... /></g></svg>');
}
LESS usage:
.element-color(#fff);
SCSS mixin:
#mixin element-color($color) {
background-image: url('data:image/svg+xml;utf8,<svg ...><g stroke="#{$color}" ... /></g></svg>');
}
SCSS usage:
#include element-color(#fff);
CSS:
// color: red
background-image: url('data:image/svg+xml;utf8,<svg ...><g stroke="red" ... /></g></svg>');
Here is more info on embedding the full SVG code into your CSS file. It also mentioned browser compatibility which is a bit too small for this to be a viable option.
One way to do this is to serve your svg from some server side mechanism.
Simply create a resource server side that outputs your svg according to GET parameters, and you serve it on a certain url.
Then you just use that url in your css.
Because as a background img, it isn't part of the DOM and you can't manipulate it.
Another possibility would be to use it regularly, embed it in a page in a normal way, but position it absolutely, make it full width & height of a page and then use z-index css property to put it behind all the other DOM elements on a page.
Yet another approach is to use mask. You then change the background color of the masked element. This has the same effect as changing the fill attribute of the svg.
HTML:
<glyph class="star"/>
<glyph class="heart" />
<glyph class="heart" style="background-color: green"/>
<glyph class="heart" style="background-color: blue"/>
CSS:
glyph {
display: inline-block;
width: 24px;
height: 24px;
}
glyph.star {
-webkit-mask: url(star.svg) no-repeat 100% 100%;
mask: url(star.svg) no-repeat 100% 100%;
-webkit-mask-size: cover;
mask-size: cover;
background-color: yellow;
}
glyph.heart {
-webkit-mask: url(heart.svg) no-repeat 100% 100%;
mask: url(heart.svg) no-repeat 100% 100%;
-webkit-mask-size: cover;
mask-size: cover;
background-color: red;
}
You will find a full tutorial here: http://codepen.io/noahblon/blog/coloring-svgs-in-css-background-images (not my own). It proposes a variety of approaches (not limited to mask).
Use the sepia filter along with hue-rotate, brightness, and saturation to create any color we want.
.colorize-pink {
filter: brightness(0.5) sepia(1) hue-rotate(-70deg) saturate(5);
}
https://css-tricks.com/solved-with-css-colorizing-svg-backgrounds/
It's possible with Sass!
The only thing you have to do is to url-encode your svg code. And this is possible with a helper function in Sass. I've made a codepen for this. Look at this:
http://codepen.io/philippkuehn/pen/zGEjxB
// choose a color
$icon-color: #F84830;
// functions to urlencode the svg string
#function str-replace($string, $search, $replace: '') {
$index: str-index($string, $search);
#if $index {
#return str-slice($string, 1, $index - 1) + $replace + str-replace(str-slice($string, $index + str-length($search)), $search, $replace);
}
#return $string;
}
#function url-encode($string) {
$map: (
"%": "%25",
"<": "%3C",
">": "%3E",
" ": "%20",
"!": "%21",
"*": "%2A",
"'": "%27",
'"': "%22",
"(": "%28",
")": "%29",
";": "%3B",
":": "%3A",
"#": "%40",
"&": "%26",
"=": "%3D",
"+": "%2B",
"$": "%24",
",": "%2C",
"/": "%2F",
"?": "%3F",
"#": "%23",
"[": "%5B",
"]": "%5D"
);
$new: $string;
#each $search, $replace in $map {
$new: str-replace($new, $search, $replace);
}
#return $new;
}
#function inline-svg($string) {
#return url('data:image/svg+xml;utf8,#{url-encode($string)}');
}
// icon styles
// note the fill="' + $icon-color + '"
.icon {
display: inline-block;
width: 50px;
height: 50px;
background: inline-svg('<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
viewBox="0 0 30 30" enable-background="new 0 0 30 30" xml:space="preserve">
<path fill="' + $icon-color + '" d="M18.7,10.1c-0.6,0.7-1,1.6-0.9,2.6c0,0.7-0.6,0.8-0.9,0.3c-1.1-2.1-0.4-5.1,0.7-7.2c0.2-0.4,0-0.8-0.5-0.7
c-5.8,0.8-9,6.4-6.4,12c0.1,0.3-0.2,0.6-0.5,0.5c-0.6-0.3-1.1-0.7-1.6-1.3c-0.2-0.3-0.4-0.5-0.6-0.8c-0.2-0.4-0.7-0.3-0.8,0.3
c-0.5,2.5,0.3,5.3,2.1,7.1c4.4,4.5,13.9,1.7,13.4-5.1c-0.2-2.9-3.2-4.2-3.3-7.1C19.6,10,19.1,9.6,18.7,10.1z"/>
</svg>');
}
.icon {
width: 48px;
height: 48px;
display: inline-block;
background: url(https://s3-us-west-2.amazonaws.com/s.cdpn.io/18515/heart.svg) no-repeat 50% 50%;
background-size: cover;
}
.icon-orange {
-webkit-filter: hue-rotate(40deg) saturate(0.5) brightness(390%) saturate(4);
filter: hue-rotate(40deg) saturate(0.5) brightness(390%) saturate(4);
}
.icon-yellow {
-webkit-filter: hue-rotate(70deg) saturate(100);
filter: hue-rotate(70deg) saturate(100);
}
codeben article and demo
Now you can achieve this on the client side like this:
var green = '3CB54A';
var red = 'ED1F24';
var svg = '<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="320px" height="100px" viewBox="0 0 320 100" enable-background="new 0 0 320 100" xml:space="preserve"> <polygon class="mystar" fill="#'+green+'" points="134.973,14.204 143.295,31.066 161.903,33.77 148.438,46.896 151.617,65.43 134.973,56.679 118.329,65.43 121.507,46.896 108.042,33.77 126.65,31.066 "/><circle class="mycircle" fill="#'+red+'" cx="202.028" cy="58.342" r="12.26"/></svg>';
var encoded = window.btoa(svg);
document.body.style.background = "url(data:image/svg+xml;base64,"+encoded+")";
Fiddle here!
Download your svg as text.
Modify your svg text using javascript to change the paint/stroke/fill color[s].
Then embed the modified svg string inline into your css as described here.
If you are trying to use and SVG directly on CSS with url() like this;
a:before {
content: url('data:image/svg+xml; utf8, <svg xmlns="http://www.w3.org/2000/svg" x="0" y="0" viewBox="0 0 451 451"><path d="M345.441,2...
You should encode the # to %23, otherwise it won't work.
<svg fill="%23FFF" ...
You can store the SVG in a variable. Then manipulate the SVG string depending on your needs (i.e., set width, height, color, etc). Then use the result to set the background, e.g.
$circle-icon-svg: '<svg xmlns="http://www.w3.org/2000/svg"><circle cx="10" cy="10" r="10" /></svg>';
$icon-color: #f00;
$icon-color-hover: #00f;
#function str-replace($string, $search, $replace: '') {
$index: str-index($string, $search);
#if $index {
#return str-slice($string, 1, $index - 1) + $replace + str-replace(str-slice($string, $index + str-length($search)), $search, $replace);
}
#return $string;
}
#function svg-fill ($svg, $color) {
#return str-replace($svg, '<svg', '<svg fill="#{$color}"');
}
#function svg-size ($svg, $width, $height) {
$svg: str-replace($svg, '<svg', '<svg width="#{$width}"');
$svg: str-replace($svg, '<svg', '<svg height="#{$height}"');
#return $svg;
}
.icon {
$icon-svg: svg-size($circle-icon-svg, 20, 20);
width: 20px; height: 20px; background: url('data:image/svg+xml;utf8,#{svg-fill($icon-svg, $icon-color)}');
&:hover {
background: url('data:image/svg+xml;utf8,#{svg-fill($icon-svg, $icon-color-hover)}');
}
}
I have made a demo too, http://sassmeister.com/gist/4cf0265c5d0143a9e734.
This code makes a few assumptions about the SVG, e.g. that <svg /> element does not have an existing fill colour and that neither width or height properties are set. Since the input is hardcoded in the SCSS document, it is quite easy to enforce these constraints.
Do not worry about the code duplication. gzip compression makes the difference negligible.
You can use the brightness filter, any value greater than 1 makes the element brighter, and any value less than 1 makes it darker. So, we can make those light SVG’s dark, and vice versa, for example, this will make the svg darker:
filter: brightness(0);
In order to change the color and not only brightness level we can use sepia filter along with hue-rotate, brightness, for example:
.colorize-blue {
filter: brightness(0.5) sepia(1) hue-rotate(140deg) saturate(6);
}
You can create your own SCSS function for this. Adding the following to your config.rb file.
require 'sass'
require 'cgi'
module Sass::Script::Functions
def inline_svg_image(path, fill)
real_path = File.join(Compass.configuration.images_path, path.value)
svg = data(real_path)
svg.gsub! '{color}', fill.value
encoded_svg = CGI::escape(svg).gsub('+', '%20')
data_url = "url('data:image/svg+xml;charset=utf-8," + encoded_svg + "')"
Sass::Script::String.new(data_url)
end
private
def data(real_path)
if File.readable?(real_path)
File.open(real_path, "rb") {|io| io.read}
else
raise Compass::Error, "File not found or cannot be read: #{real_path}"
end
end
end
Then you can use it in your CSS:
.icon {
background-image: inline-svg-image('icons/icon.svg', '#555');
}
You will need to edit your SVG files and replace any fill attributes in the markup with fill="{color}"
The icon path is always relative to your images_dir parameter in the same config.rb file.
Similar to some of the other solutions, but this is pretty clean and keeps your SCSS files tidy!
If you wanna swap in a simple way from white to black or some like that, try this:
filter: invert(100%);
In some (very specific) situations this might be achieved by using a filter. For example, you can change a blue SVG image to purple by rotating the hue 45 degrees using filter: hue-rotate(45deg);. Browser support is minimal but it's still an interesting technique.
Demo
for monochrome background you could use a svg with a mask, where the background color should be displayed
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" preserveAspectRatio="xMidYMid meet" focusable="false" style="pointer-events: none; display: block; width: 100%; height: 100%;" >
<defs>
<mask id="Mask">
<rect width="100%" height="100%" fill="#fff" />
<polyline stroke-width="2.5" stroke="black" stroke-linecap="square" fill="none" transform="translate(10.373882, 8.762969) rotate(-315.000000) translate(-10.373882, -8.762969) " points="7.99893906 13.9878427 12.7488243 13.9878427 12.7488243 3.53809523"></polyline>
</mask>
</defs>
<rect x="0" y="0" width="20" height="20" fill="white" mask="url(#Mask)" />
</svg>
and than use this css
background-repeat: no-repeat;
background-position: center center;
background-size: contain;
background-image: url(your/path/to.svg);
background-color: var(--color);
Since this comes up on Google despite the age, I thought I might as well give a solution that I'm employing in the distant future of 2022 after looking at the options here.
This is really just the mask solution from before, but on a pseudo-element.
.icon {
height: 1.5rem;
width: 1.5rem;
}
.icon::before {
content: "";
display: block;
width: 100%;
height: 100%;
mask-repeat: no-repeat;
mask-position: center;
mask-size: contain;
mask-image: url("path/to/svg/icon.svg");
-webkit-mask-repeat: no-repeat;
-webkit-mask-position: center;
-webkit-mask-size: contain;
-webkit-mask-image: url("path/to/svg/icon.svg");
}
This works in all major browsers today, although obviously you can't have an SVG with multiple colors using this. That's the cost of business if the site doesn't let you inject them inline, or if you don't fancy doing font icons, etc.
Late to the show here, BUT, I was able to add a fill color to the SVG polygon, if you're able to directly edit the SVG code, so for example the following svg renders red, instead of default black. I have not tested outside of Chrome though:
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
width="500px" height="500px" viewBox="0 0 500 500" enable-background="new 0 0 500 500" xml:space="preserve">
<polygon
fill="red"
fill-rule="evenodd" clip-rule="evenodd" points="452.5,233.85 452.5,264.55 110.15,264.2 250.05,390.3 229.3,413.35
47.5,250.7 229.3,86.7 250.05,109.75 112.5,233.5 "/>
</svg>
The only way i found for this, and to be cross browser (aka bulletproof), is to render the SVG with PHP and pass Query String to set the color.
The SVG, here called "arrow.php"
<?php
$fill = filter_input(INPUT_GET, 'fill');
$fill = strtolower($fill);
$fill = preg_replace("/[^a-z0-9]/", '', $fill);
if(empty($fill)) $fill = "000000";
header('Content-type: image/svg+xml');
echo '<?xml version="1.0" encoding="utf-8"?>';
?>
<svg xmlns="http://www.w3.org/2000/svg" width="7.4" height="12" viewBox="0 0 7.4 12">
<g>
<path d="M8.6,7.4,10,6l6,6-6,6L8.6,16.6,13.2,12Z" transform="translate(-8.6 -6)" fill="#<?php echo htmlspecialchars($fill); ?>" fill-rule="evenodd"/>
</g>
</svg>
Then you call the image like this
.cssclass{ background-image: url(arrow.php?fill=112233); }
Works only with PHP. And remember that everytime you change the color value, your browser will load a new image.
scss create function
#function url-svg($icon) {
#return url("data:image/svg+xml;utf8,#{str-replace($icon, "#", "%23")}");
}
scss use
url-svg('<svg width="15" height="15" viewBox="0 0 15 15" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M13.125 0H1.875C0.84082 0 0 0.84082 0 1.875V10.3125C0 11.3467 0.84082 12.1875 1.875 12.1875H4.6875V14.6484C4.6875 14.9355 5.01563 15.1025 5.24707 14.9326L8.90625 12.1875H13.125C14.1592 12.1875 15 11.3467 15 10.3125V1.875C15 0.84082 14.1592 0 13.125 0Z" fill="#8A8A8F"/></svg>')
css generated
url('data:image/svg+xml;utf8,<svg width="15" height="15" viewBox="0 0 15 15" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M13.125 0H1.875C0.84082 0 0 0.84082 0 1.875V10.3125C0 11.3467 0.84082 12.1875 1.875 12.1875H4.6875V14.6484C4.6875 14.9355 5.01563 15.1025 5.24707 14.9326L8.90625 12.1875H13.125C14.1592 12.1875 15 11.3467 15 10.3125V1.875C15 0.84082 14.1592 0 13.125 0Z" fill="%238A8A8F"/></svg>')
The str-replace function is used from bootstrap.
Here is another solution using a gradient and a monochrome icon as background and background-blend-mode to colorize the icon.
It requires the background-color to be white, else the whole background gets colored. I only tested on Chrome.
.colored-background {
background-image: linear-gradient(45deg, green, green), url('data:image/svg+xml;charset=US-ASCII,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%22292.4%22%20height%3D%22292.4%22%3E%3Cpath%20fill%3D%22%23000000%22%20d%3D%22M287%2069.4a17.6%2017.6%200%200%200-13-5.4H18.4c-5%200-9.3%201.8-12.9%205.4A17.6%2017.6%200%200%200%200%2082.2c0%205%201.8%209.3%205.4%2012.9l128%20127.9c3.6%203.6%207.8%205.4%2012.8%205.4s9.2-1.8%2012.8-5.4L287%2095c3.5-3.5%205.4-7.8%205.4-12.8%200-5-1.9-9.2-5.5-12.8z%22%2F%3E%3C%2Fsvg%3E');
background-color: #fff;
background-blend-mode: lighten, normal;
background-repeat: no-repeat;
background-position: center, center right .8em;
background-size: auto, 0.6em;
color: red;
display: inline-flex;
align-items: center;
padding: 0.5em;
padding-right: 2em;
height: 1.6em;
width: auto;
border: 1px solid gray;
}
.bg {
background-color: #ddd;
padding: 1em;
}
<div class="bg">
<div class="colored-background">green icon from black svg</div>
</div>
Related to a closed question that is linked to here, but not related directly to this question.
So in case, anyone needs actually to replace src like in the linked question, there is already an answer there. Furthermore if anyone is coming from Vue, and the src path is change on compile, I've come up with a different solution.
In my case, the parent element is a link, but it could be anything really.
<a
v-for="document in documents" :key="document.uuid"
:href="document.url"
target="_blank"
class="item flex align-items-center gap-2 hover-parent"
>
<img alt="documents" class="icon" src="../assets/PDF.svg" />
<strong>{{ document.name }}</strong>
<img class="itemImage ml-auto hide-on-parent-hover" src="../assets/download-circular-button.svg" />
<img class="itemImage ml-auto show-on-parent-hover" src="../assets/download-circular-button-hover.svg" />
</a>
.hover-parent .show-on-parent-hover { display: none }
.hover-parent .hide-on-parent-hover { display: block }
.hover-parent:hover .show-on-parent-hover { display: block }
.hover-parent:hover .hide-on-parent-hover { display: none }
So the solution here is not to change src attribute, but instead to put both <img> elements in the DOM and only display the one that is needed.
If you don't have a parent element that's supposed to be hovered on, you can simply wrap both images in a div.
<div class="hover-parent" >
<img class="hide-on-parent-hover" src="../assets/download-circular-button.svg" />
<img class="show-on-parent-hover" src="../assets/download-circular-button-hover.svg" />
</div>
You might also change CSS to the following, so the .hover-parent ancestor must be a direct parent:
.hover-parent > .show-on-parent-hover { display: none }
.hover-parent > .hide-on-parent-hover { display: block }
.hover-parent:hover > .show-on-parent-hover { display: block }
.hover-parent:hover > .hide-on-parent-hover { display: none }
This is my favorite method, but your browser support must be very progressive. With the mask property you create a mask that is applied to an element. Everywhere the mask is opaque, or solid, the underlying image shows through. Where it’s transparent, the underlying image is masked out, or hidden. The syntax for a CSS mask-image is similar to background-image.look at the codepenmask
A lot of IFs, but if your pre base64 encoded SVG starts:
<svg fill="#000000
Then the base64 encoded string will start:
PHN2ZyBmaWxsPSIjMDAwMDAw
if the pre-encoded string starts:
<svg fill="#bfa76e
then this encodes to:
PHN2ZyBmaWxsPSIjYmZhNzZl
Both encoded strings start the same:
PHN2ZyBmaWxsPSIj
The quirk of base64 encoding is every 3 input characters become 4 output characters. With the SVG starting like this then the 6-character hex fill color starts exactly on an encoding block 'boundary'.
Therefore you can easily do a cross-browser JS replace:
output = input.replace(/MDAwMDAw/, "YmZhNzZl");
But tnt-rox answer above is the way to go moving forward.

Imitate Photoshop blend effects like multiply, overlay etc

I'm making a website with a full page background image. I want to create a background image for a side column that acts like a Photoshop layer with multiply as blend mode. It's just a blue colored surface with the 'behaviour' of a Photoshop multiply layer.
It's not possible to merge the overlay and the image since the background can change when the website is opened in another screen ratio/size.
There are a lot of solutions on SO, but they only work with multiplying 2 images with a fixed position, not a colored surface with variable position/background.
Are there tricks to achieve this?
jsBin demo
Use the CSS3 property mix-blend-mode MDN Docs
(For fallback use an rgba or hsla color with a bit of alpha transparency.)
Assign a desired blend-* class to your element like:
/* ::: BLEND MODE CLASSES */
.blend-normal{ mix-blend-mode: normal; }
.blend-multiply{ mix-blend-mode: multiply; }
.blend-screen{ mix-blend-mode: screen; }
.blend-overlay{ mix-blend-mode: overlay; }
.blend-darken{ mix-blend-mode: darken; }
.blend-lighten{ mix-blend-mode: lighten; }
.blend-colordodge{ mix-blend-mode: color-dodge; }
.blend-colorburn{ mix-blend-mode: color-burn; }
.blend-hardlight{ mix-blend-mode: hard-light; }
.blend-softlight{ mix-blend-mode: soft-light; }
.blend-difference{ mix-blend-mode: difference; }
.blend-exclusion{ mix-blend-mode: exclusion; }
.blend-hue{ mix-blend-mode: hue; }
.blend-saturation{ mix-blend-mode: saturation; }
.blend-color{ mix-blend-mode: color; }
.blend-luminosity{ mix-blend-mode: luminosity; }
/* ::: SET HERE YOUR INITIAL COLORS */
div{
background: rgba(0, 80, 200, 0.8);
color: #fff;
}
div span{
color:#000;
}
/* ::: FOR DEMO ONLY */
html, body{margin:0; height:100%;font:100%/1 sans-serif;}
body{background: url(http://i.stack.imgur.com/cBy6q.jpg)fixed 50%/cover;}
div{font-size:2.2em; padding:20px; margin:15px;}
div:first-of-type{margin-top:150px;}
div:last-of-type{margin-bottom:150px;}
<div class="">(rgba) <span>(rgba)</span></div>
<div class="blend-normal">normal <span>normal</span></div>
<div class="blend-multiply">multiply <span>multiply</span></div>
<div class="blend-screen">screen <span>screen</span></div>
<div class="blend-overlay">overlay <span>overlay</span></div>
<div class="blend-darken">darken <span>darken</span></div>
<div class="blend-lighten">lighten <span>lighten</span></div>
<div class="blend-colordodge">color-dodge <span>color-dodge</span></div>
<div class="blend-colorburn">color-burn <span>color-burn</span></div>
<div class="blend-hardlight">hard-light <span>hard-light</span></div>
<div class="blend-softlight">soft-light <span>soft-light</span></div>
<div class="blend-difference">difference <span>difference</span></div>
<div class="blend-exclusion">exclusion <span>exclusion</span></div>
<div class="blend-hue">hue <span>hue</span></div>
<div class="blend-saturation">saturation <span>saturation</span></div>
<div class="blend-color">color <span>color</span></div>
<div class="blend-luminosity">luminosity <span>luminosity</span></div>
Simple with a bit of SVG:
<svg width="200" height="200" viewBox="10 10 280 280">
<filter id="multiply">
<feBlend mode="multiply"/>
</filter>
<image id="kitten" x="0" y="0" width="300" height="300" xlink:href="http://placekitten.com/300" />
</svg>
and some CSS:
#kitten:hover {
filter:url(#multiply);
}
The fiddle: http://jsfiddle.net/7uCQQ/
As FC said you can use CSS3 custom filters or SVG/Canvas.
But if you need a cross-browser solution for blending layers you have to use JS method. For example, JS image processing script from Pixastic: http://www.pixastic.com/lib/docs/actions/blend/
In addition it has a lot of other visual effects like blur, noise, crop, mosaic etc.
I used this script before for several projects, it works realy great :)
Hope it helps you)
I'm a designer and had the same problem, looking for solutions before putting the psd over to the dev team - you can try this js and/or http://css-tricks.com/basics-css-blend-modes/
Jsfiddle code:
#kitten:hover {
filter:url(#multiply);
}
<svg width="200" height="200" viewBox="10 10 280 280">
<filter id="multiply">
<feBlend mode="multiply"/>
</filter>
<image id="kitten" x="0" y="0" width="300" height="300" xlink:href="http://placekitten.com/300" />
</svg>
Hope it works for you or others here. :)

Resources