Article
2 comments

SVG background in CSS without base64 encoding – Possible?

While working on a side project, I asked myself the interesting question if it would be possible to use SVG in CSS as a background image.
It is relatively simple if you use the SVG as an external file, but what if the object of the background is simple and I like to use it directly as an SVG is CSS.

SVG in CSS without base64

In the past, I always base64 encode the source of the SVG image, which is not needed.

Issues with SVG

For the first attempt, I tried just a simple SVG in the form of a blue rectangle.

<svg width="300" height="100">
    <rect width="300" height="100" style="fill: blue" />
</svg>

The first thing to transform this to work in CSS was to convert the double quotes to single quotes and make the string just one line.

See the Pen Failing SVG Background by Stefan Bauer (@StfBauer) on CodePen.dark

So I thought, but something essential was missing, and the background was unable to load even though the web inspector in any browser showed no problem.

The missing piece here was the XML namespace on the SVG element ‘xmlns=”http://www.w3.org/2000/svg”‘.

After fixing this, everything worked perfectly.

See the Pen Fixed SVG Background by Stefan Bauer (@StfBauer) on CodePen.dark

Time to try out some more complex background, for example, a star.

Complex SVG backgrounds

Let’s say we like to use the following SVG image that is more complex than a simple rectangle.

SVG Star Tryout

SVG Star Tryout

This extraordinary piece of art I created in Adobe Illustrator, and it also works as expected.

Exporting from Illustrator

There is one small catch when you export the image using the ‘Export for Screen’ option.

Adobe Illustrator Export settings

Adobe Illustrtor Export settings

The default setting for SVG is ‘Inplace CSS’ this needs to get changed to ‘Inline CSS’ otherwise the image won’t show up too. The problem is that it would load a CSS inside the SVG image, which from my testing only works for inline CSS.

2 Comments

Leave a Reply

Required fields are marked *.


This site uses Akismet to reduce spam. Learn how your comment data is processed.