Lucas Rees
building blocks
Published in
2 min readJul 14, 2015

--

code snippet

manipulate SVG images with CSS on Interaction

(using jQuery SVG image replacement)

SVGs (short term for Scalable Vector Graphics) are awesome, because they’re made out of XML-tags which can be interacted with and animated much like HTML elements can be.

If you want to style a SVG with CSS you have to write its styles inside the SVG itself, if you want to interact with a SVG with CSS (change its fill or outline on :hover for example) on the other hand, you have to write the SVG code straight inline the main DOM instead of using an external SVG-file. There are several reasons why you don’t want to, should not or even can’t do either, though — being impractical and rigid for example.

With a little help of our old trusted friend jQuery you can still use external SVG-files but manipulate the image with plain CSS from your regular, external stylesheet. Simply add a class (for example svg) to the img-tags with an SVG you want to manipulate:

and call this jQuery function when you load your document:

It’ll go through the document and replace every IMG-tag with the class ‘svg’ with the inline SVG from the linked file, keeping the ID and all the attached classes. Afterwards you can target the parts of the SVG pretty easy with CSS:

Unfortunately there’s no way to manipulate SVGs linked in the CSS-file itself (with the background or background-image). Even if you go crazy and write the SVG-code in the CSS directly like this instead:

there’s no way of manipulating it with CSS, because it’s not part of the DOM and therefore not targetable by CSS.

At least there’s a solution for the IMG-tags.

--

--

Lucas Rees
building blocks

Graphic designer, code writer, maker of things — obsessed with form and function, structure and material — crafting digital stuff for wagnerwagner.de