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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With