Styling SVG Sucks So Far
I'm currently working on a site that I'd like to make use of SVGs with, but I've ran into an issue.
The site's a long one page scroller and has multiple complex SVGs.
I started by adding in SVG elements to the index.html file, but I soon ended up with a huge file to manage. Some of the SVG code is around the 200 line mark. So I opted to create <div class="svg-mysvg"></div>
then use CSS to add the SVG in as a background image making the file much more manageable.
1 | .svg-mysvg { |
However, herein lies a problem:
@s10wen the SVG's dom doesn't exist as part of the document when it's a bg image.
— Jake Archibald (@jaffathecake) February 20, 2014
Adding an SVG as a background image means the SVG isn't part of the dom so we lose styling.
For example with an SVG element in the dom, we can simply change the colour with fill
in CSS as Chris Coyier demonstrates:
See the Pen SVG with Filters by Chris Coyier (@chriscoyier) on CodePen.
I suggested perhaps something along these lines:
1 | .svg { |
But as Chris Coyier points out:
@s10wen Would be convenient sometimes, but I’d worry svg sub-elements would be affect by wayward CSS. It would be a weird precedent to set.
— Chris Coyier (@chriscoyier) February 20, 2014
This could get confusing with SVG sub-elements.
I've also tried using the object
tag, but this also doesn't seem to work:
See the Pen HeFIu by Simon Owen (@s10wen) on CodePen.
The ideal solution I'm looking for:
- Rather than embed 100s of lines for each SVG, have a one liner that calls to a separate SVG file.
- Have full control over styling with CSS.
Hopefully I'm missing something, but so far I haven't found a great solution.
I'd love to hear anyone else's thoughts on this.
Feedback
Thanks for the feedback folks!
@s10wen you can use SVG attributes in CSS, given that that SVG will be embedded into the DOM somehow (ajax load or embedded into HTML)
— Bobby Bobak (@bobek_balinek) February 22, 2014
@s10wen Templating / ajax-include then. I don't think this should be solved with CSS syntax, blurring the line between DOM & linked assets
— Stu Cox (@StuCoxMedia) February 22, 2014
@s10wen @chriscoyier @aerotwist @paul_irish @aerotwist @jaffathecake @csswizardry In these situations I link to CSS file from inside the SVG
— Ben Frain (@benfrain) February 22, 2014
@s10wen for the sake of it could you use PHP include? Then separate things like modules?
— Morgan Feeney (@MorganFeeney) February 22, 2014
Browse by category:
- apple1
- bash1
- browser1
- case study4
- chrome2
- chrome dev tools4
- clojure overtone2
- conference2
- css2
- dev tips1
- digihike1
- dotfiles2
- event4
- ffconf1
- freelance6
- gaming2
- health3
- hexo1
- https1
- jank1
- javascript1
- jobs1
- lego1
- mcrfred107
- nux1
- octopress4
- photography2
- raspberry pi1
- responsive web design1
- sass1
- screencast1
- speaking2
- svg4
- unplugged6
- upfrontconf1
- web development2
- webgl1
- wordpress17
- work51
- workflow16