Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store multiple elements in SVG & use them as CSS backgrounds?

Tags:

css

svg

I'm wondering if I can create multiple "brushes" in a single SVG file and use them thoughout my CSS.

Right now I have a single SVG file that has a gradient stored in the "defs" and a single rectangle that draws it. Then I use this SVG file as a background image in my CSS. It works well but I'd rather not have a million separate SVG files. I'd like to combine like "brushes" together in a single SVG file something like CSS sprites or XAML is capable of.

Is there a way to do this? If so what's the syntax to specify for the CSS background image which SVG element from the svg file to use?

Thanks for any help.

like image 863
user169867 Avatar asked Apr 16 '11 23:04

user169867


People also ask

How to group elements in SVG?

Grouping elements with the elementThe <symbol> element is similar to the group element <g> —it provides a way to group elements together.

Can SVG elements be nested?

The SVG format allows for the nesting of SVG graphics. It is possible for an “<svg>” elements, to be placed within another “<svg>” element. Though, within a nesting, the absolute placement is limited to the respective parent “<svg>” element.

What should you do to reuse an SVG image multiple times easily and clearly?

The SVG <use> element can reuse an SVG shape from elsewhere in the SVG document, including <g> elements and <symbol> elements.


1 Answers

In theory yes, that should be possible. It's not yet fully defined in a w3c spec though and the implementations do differ at this stage.

Note that svg itself allows a special fragment syntax, so in theory you should be able to link to different views of the same svg file. That could be used to do CSS/SVG sprites.

Linking directly to the id of a nested svg fragment (or to any other element inside the svg) is something that would need to be further specified.

Assuming that linking with fragments from a CSS background property works, then a possibility if you use XHTML (serving the resulting file as application/xhtml+xml) is to just include the svg resources inline in the main document, eliminating the need for many separate files. This can be done as a pre-publishing buildstep if you wish to keep the svgs separate for editing. Another possibility is to use data uris.

like image 134
Erik Dahlström Avatar answered Sep 19 '22 12:09

Erik Dahlström