Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inline SVG in CSS

Tags:

css

svg

Is it possible to use an inline SVG definition in CSS?

I mean something like:

.my-class {   background-image: <svg>...</svg>; } 
like image 396
akaRem Avatar asked May 26 '12 17:05

akaRem


People also ask

How do I create an inline 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.

Can you put 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 inline SVG?

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.

What is inline SVG?

Inline SVG simply refers to SVG markup that is included in the markup for a webpage.


1 Answers

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>");       } 
  • http://jsfiddle.net/6WAtQ/

(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.

like image 53
Raab Avatar answered Oct 13 '22 09:10

Raab