Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use SVG symbols in CSS?

Tags:

Using symbols in SVG formats seems like a good idea to me, so you can only load a single SVG file, and use it as a sort of spritemap.

It feels wrong to me though, to directly include the <svg></svg> tags in my html for icons, since they are presentation only and should be added in my CSS.

Is there a way to add a symbol from an svg in an :after pseudo element in my CSS?

like image 462
enyo Avatar asked Aug 07 '14 13:08

enyo


People also ask

How do I use SVG in CSS?

We can use SVG in CSS via data URI, but without encoding it works only in Webkit based browsers. If encode SVG using encodeURIComponent() it will work everywhere. SVG must have attribute xmlns like this: xmlns='http: //www.w3.org/2000/svg' . If it doesn't exist, it will be added automagically.

Can I use SVG in CSS content?

Modern browsers support using SVG within CSS styles to apply graphical effects to HTML content. You may specify SVG in styles either within the same document or an external style sheet.

How use SVG icons in HTML CSS?

SVG images can be written directly into the HTML document using the <svg> </svg> tag. To do this, open the SVG image in VS code or your preferred IDE, copy the code, and paste it inside the <body> element in your HTML document.

How do I use an SVG symbol?

The SVG <symbol> element is used to define graphical template objects which can be instantiated by the <use> element. The use of symbol elements for graphics that are used multiple times in the same document adds structure and semantics.


1 Answers

You can refer to fragments in CSS this way (fragments must have an ID to identified):

.element {
background-image: url('vector.svg#fragment');
}

You can also show a specific area by clipping it with viewBox:

.element {
background-image: url('vector.svg#fragment(viewBox(0,0,25,25))');
}

Here you can read more about this methods: http://www.broken-links.com/2012/08/14/better-svg-sprites-with-fragment-identifiers/

Another method could be to create all your symbols in a icon font.

like image 160
blacksunshineCoding Avatar answered Sep 20 '22 00:09

blacksunshineCoding