I have an SVG file that I want to use in a web page. I want the image to appear multiple times, but to apply different CSS styles to each one.
Is this possible?
Clarification
When I say "apply different CSS styles", I mean that I want to style the SVG contents (stroke, color, radius, etc), not just the width of an <img>
or something.
Also, I don't consider "copy and paste the SVG contents" to be "re-using" it. I want to create a file like logo.svg
and reference it from the HTML.
Demo
html
css
You can use it this way if you don't want to use the whole values of
svg
multiple times.Demo
html
css
source : http://css-tricks.com/using-svg/
No, not currently
Styling the contents (stroke, fill, etc) of an SVG from a containing HTML document is currently not supported.
@RobertLongson was kind enough to point me to the SVG Parameters spec, which could provide a partial solution. It is not implemented in any browser, but can be used with a Javascript shim. However, when I emailed the SVG working group with a question about it, I was told:
And
A non-spec-compliant hack: the
use
tagFor the record, the following seemed to accomplish my stated goals (technique borrowed from CSS-Tricks), but @RobertLongson let me know that it only worked in Firefox (I think I was using version 31) because Firefox was not compliant with the spec.
Even if it were standard, this technique would be less than ideal; the ideal solution would allow using an SVG defined in an external file, like
circles.svg
.This is because:
Yes, it can be easily done using SVG injection, and it should work on all Browsers that support SVG.
With SVGInject your HTML may look like this:
The
onload="SVGInject(this)"
triggers the injection after the SVG is loaded and replaces the<img>
element with the SVG markup from the specified SVG file.Yes, absolutely!
If each occurrence is unique, simply apply an
id
attribute to thesvg
then reference it and its children with the id prefixing any selectors, e.g<svg id='myimage ... />
Then in your css:
#myimage line{...}
Would for example apply styles to the
line
elements within themyimage
svg.I'd also recommend having a look at the MDN article on CSS selectors