3

We're using SVGs for the first time for our mobile HTML5 based app sprites file (they make dealing with retina an other screen size differences easy).

I know generated SVGs can be manipulated directly (as they are text files) but can one modify an SVG asset (in this case, a background image loaded via the CSS) via CSS or scripting?

For instance, can we load an all-black SVG object, and then change it to white?

Erik Dahlström
  • 59,452
  • 12
  • 120
  • 139
DA.
  • 39,848
  • 49
  • 150
  • 213

1 Answers1

6

You can't access the DOM of the SVG file if it's loaded as an image (either through img or background-image). You can't style it via CSS either.

If you intend to do these kind of manipulations you should append the SVG to a div. You should still be able to perform sprite-like manipulations to that div. You will be able to style it via CSS or javascript.


The SVG should be inlined. You can copy and paste the SVG into the div that used to contain background-image or load it there through an ajax request.

Instead of animating background-position you can animate with left or -webkit-transform: translate(...).

methodofaction
  • 70,885
  • 21
  • 151
  • 164
  • Can you explain the second part? What do you mean append it to the div? – DA. Nov 15 '12 at 05:49
  • Thanks! How would one use it as a sprite sheet, however, when inline? Can you mask portions of an inline SVG? – DA. Nov 15 '12 at 16:03
  • Just add a parent div with `overflow: hidden` – methodofaction Nov 15 '12 at 16:52
  • Thanks, Duopixel. That makes perfect sense for sprite usage. I'm still a bit confused about how to add the SVG to the DOM. By 'inlined' do you mean I should be using an actual SVG tag in the HTML itself? I think that would technically work, but is bit impractical for our needs. Oh well. It was worth experimenting a bit! – DA. Nov 19 '12 at 04:24