How to Inline SVG in CSS
In many cases, an inlined SVG feels like a bit of noise in HTML. An icon feels more like styling than content that should be part of the DOM structure. The good news is, we can move SVG images entirely into CSS.
Hamburger Menu Button
Let’s take the hamburger menu button on this page in the top right corner. In HTML, the button is simply an anchor element with a class.
Then, in CSS, we can set a background-image
property. For this CSS property, we usually provide a link to an image, but we can also inline an SVG.
Some characters need to be escaped when inlining an SVG in CSS’s url
function. The #
character for instance, becomes %23
.
The inlined SVG above is the same hamburger menu icon as we created in the basic paths chapter. The only difference is that we changed its width
and height
to match the button’s size, and we set the XML namespace.
When we inline an SVG in CSS, we need to set the XML namespace property. Earlier we inlined SVGs into HTML and in that case it’s optional. In CSS we have to set the xmlns
property.
Custom Mouse Cursor with SVG in CSS
Have you ever wondered how to make your website stand out? One way is to set custom mouse cursors. Take a look at this page. Do you notice how the cursor isn’t the usual one? I’ve taken over the custom cursors from figma.com.
Here’s an example of a custom mouse cursor that’s a simple arrow.
Then, you can override the value of the default cursor in the following way. Note that changing the default cursor will override all types of cursors on your page.
Changing the cursor the above way will override all types of cursors on your page. Be sure to set the cursor back to the initial value for HTML elements that require something else (this list is not comprehensive).
Background Patterns with SVG in CSS
We can also use this technique to generate a background pattern. By default if the image we define in background-image
is smaller than the element itself, then the image will repeat itself.
In the main example for today we simply repeat the following SVG:
In this example we encode some special characters in the inlined string. In the example below we encode the pointy brackets (<
and >
) and the #
key in the color value to make sure it works in every browser. This makes it hard to read, but what we have here is still a simple SVG.
You might also note that this SVG image doesn’t even have a background color set. We set that in CSS.
This is a great way to create background patterns with only a few lines of code in CSS. If you like this idea check out svgbackgrounds.com for a lot more great patterns.