Search code examples
csssvg

Inline SVG in CSS


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

I mean something like:

.my-class {
  background-image: <svg>...</svg>;
}

Solution

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