Using SVG
Use SVG Icons directly in your stylesheet without using Data URIS and recolour on demand with variables.
We built this into Slate to facilitate adding the triangle to the custom select boxes, but you can totally use it in your projects too. It's great for simple things like custom bullets where an external SVG or a sprite sheet is overkill. Let's make a fancy phone link using a custom SVG.
The first thing to do is to get your SVG code into a variable. Save your SVG and minify with something like SVGOMG to make it as small as possible. We are using a Telephone icon from the html entities listed at HTML Arrows.
The important thing to note here is the fill value fill="#000000"
. It must be set to black (aka #000000
). This is because the SVG function looks for the black fill and then replaces it with the desired color.
Let's set this code as the value of a variable, by giving it a name and wrapping it in single quotes:
$telephone: '<svg viewBox="0 0 25 19" xmlns="http://www.w3.org/2000/svg" >...</svg>';
So far so good. Now, we can use the helper mixin to add it as a background image on an element. Either set the elements width and height large enough to cover the image, or use background-size
.
.tel-btn {
position: relative;
padding: 8px 8px 8px 43px;
background-color: #eee;
text-transform: uppercase;
font-weight: $semibold;
margin: 0 auto rem(24px);
display: inline-block;
&:before {
@include svgbg($telephone);
position: absolute;
content: '';
width: 25px;
height: 19px;
background-size: cover;
margin: 2px 0 0 -35px;
}
&:hover {
color: $secondary;
}
}
Easy enough. That will just spit out the SVG as nature intended, with all the special characters made CSS safe, but without modifying the colours at all. Lets take it a little further, and see it context. The button below was made using that function.
Call us now!The mixin also supports setting new colours on the fly. The mixin assumes the colour of your default icon is black (#000000
). If your icons have a different background colour, you set this colour globally in _settings.svg.scss
.
If you have a rogue icon that does not have a default black fill, you can set a third option on the mixin to reset the icons initial colour to something else. You must, however, wrap it in single quotes because the function the mixin relies on to change the colour expects a string value.
@include svgbg($telephone, $bright, '#f0f0f0');
The above example will swap the icons original colour of #f0f0f0
to the value of the $bright
variable defined in _settings.colors.scss
.