Matt Stone
Matt Stone

Reputation: 3900

Using CSS to insert and color an SVG from a spritesheet

I'm using svg-sprite to generate a SVG spritesheet to be embedded via the <use> method:

<svg class="icon">
  <use xlink:href="/assets/icons.svg#phone"/>
</svg>

This works nicely for embedding and styling icons via HTML markup.

However, I also need the option to embed icons purely via CSS. For example adding a content list via the CMS WYSIWYG editor should not requiring the content editor to add extra SVG elements.

For example:

<ul class="icon-list">
  <li>Item 1</li>
  <li>Item 2</li>
</ul>

.icon-list li::before { /* icon here */ }

Is there a way to achieve this with the <use> embed method, or a similar method? The solution also needs to allow for colouring the SVG via CSS.

Upvotes: 0

Views: 115

Answers (1)

Paul LeBeau
Paul LeBeau

Reputation: 101820

If I understand your question correctly, the basic answer is no.

You can include an SVG icon in the CSS, just as you could a bitmap one. For example with background-image. However due to browser privacy restrictions, it has to be self contained. It cannot refer to external SVG elements with <use>. Or in fact any external object - such as other images, fonts etc.

It also cannot be styled with outside CSS. So, for example, if you needed different colour variants of the same icon, you would need to create a separate SVG for each colour.

Upvotes: 1

Related Questions