Adding SVG to the background using inline CSS

I realised that there are some articles on this site that would benefit from an info box. I could mention a topic, and then go into more detail without straying too far from the purpose of the article.

Structurally, I want the code to look like this:

<aside class="info">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce viverra, mi at vulputate interdum, dui elit volutpat leo, eu laoreet diam lacus et ante.</aside>

Which will render an element like this:

Info box

The challenges are:

  • Can I get the image to appear without adding an img element inside the info box?
  • Can I do so without loading the SVG separately (to reduce the number of requests)?

The answer to both is yes, and the key lies with background-image.

Using inline SVG in CSS

Typically, background-image requires a URL, but we can also provide the SVG data directly.

Let's take the following SVG:

<svg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24'>
	<path d='M12 0c-6.627 0-12 5.373-12 12s5.373 12 12 12 12-5.373 12-12-5.373-12-12-12zm1 18h-2v-6h-2v-2h4v8zm-1-9.75c-.69 0-1.25-.56-1.25-1.25s.56-1.25 1.25-1.25 1.25.56 1.25 1.25-.56 1.25-1.25 1.25z'/>
</svg>

We can write that within a data URI scheme. In other words, in this format:

data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24'>
	<path d='M12 0c-6.627 0-12 5.373-12 12s5.373 12 12 12 12-5.373 12-12-5.373-12-12-12zm1 18h-2v-6h-2v-2h4v8zm-1-9.75c-.69 0-1.25-.56-1.25-1.25s.56-1.25 1.25-1.25 1.25.56 1.25 1.25-.56 1.25-1.25 1.25z'/>
</svg>

And by putting that inside the background-image URL, along with some other rules:

aside.info {
	background-image: url("data:image/svg+xml,	<svg xmlns='http://www.w3.org/2000/svg' width='24' height='24' fill='rgb(72, 168, 216)' viewBox='0 0 24 24'><path d='M12 0c-6.627 0-12 5.373-12 12s5.373 12 12 12 12-5.373 12-12-5.373-12-12-12zm1 18h-2v-6h-2v-2h4v8zm-1-9.75c-.69 0-1.25-.56-1.25-1.25s.56-1.25 1.25-1.25 1.25.56 1.25 1.25-.56 1.25-1.25 1.25z'/></svg>");	background-repeat: no-repeat;	
	/* Other fields to make it look pretty */
	padding: 15px;
    padding-left: 60px;	
	background-color: rgba(72, 168, 216, 10);
	border: 1px solid rgba(72, 168, 216, 10);
    background-position-y: center;
    background-position-x: 18px;
}

Note that I've also included background-repeat: no-repeat;. This prevents the image from repeating itself both vertically and horizontally across the element.

And the final result?

This is what I put directly into markdown:

<aside class="info">This is an info box. It contains lots of useful information.</aside>

<!-- I added a danger box too, with the same technique -->
<aside class="danger">This is a danger box. How ominous!</aside>