Is it possible to use an inline SVG definition in CSS?
I mean something like:
.my-class { background-image: <svg>...</svg>; }
How to use inline SVG images. 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.
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.
Aside from using it as a classic image file via the “<img>” element, SVG can also be implemented via “<object>” or “<iframe>”. The latter two have the advantage that they allow for the execution of JavaScript and animations. The simple variant however, is marking SVG inline in the HTML source code.
Inline SVG simply refers to SVG markup that is included in the markup for a webpage.
Yes, it is possible. Try this:
body { background-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='10' height='10'><linearGradient id='gradient'><stop offset='10%' stop-color='%23F00'/><stop offset='90%' stop-color='%23fcc'/> </linearGradient><rect fill='url(%23gradient)' x='0' y='0' width='100%' height='100%'/></svg>"); }
(Note that the SVG content needs to be url-escaped for this to work, e.g. #
gets replaced with %23
.)
This works in IE 9 (which supports SVG). Data-URLs work in older versions of IE too (with limitations), but they don’t natively support SVG.
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