• Post Reply Bookmark Topic Watch Topic
  • New Topic

Practical SVG: best way to get SVG into the HTML?  RSS feed

 
Bear Bibeault
Author and ninkuma
Marshal
Posts: 66307
152
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hard-coding the SVG element into the HTML works great, but just seems so wrong; repeating the element every time an icon is needed. (And using a server-side include mechanism seems like cheating, and for SPAs is generally not feasible.)

Using the <img> tag has its limitations.

What's the most practical way to get SVG onto the page?
 
Chris Coyier
Author
Greenhorn
Posts: 7
5
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There are two potential problems with repeating the inline <svg> code over and over in HTML:

1) It's kinda ugly and unwieldy
2) Mayyyyybe: DOM weight.

I wouldn't worry about #2 very much though unless you're in an extreme situation (e.g. thousands of uses).

To solve 1, there are plenty of abstractions available. Grunticon lets you use <span>s and then progressively enhances up to an inline svg: https://github.com/filamentgroup/grunticon

The best though, I think, is that SVG has a <use> element baked right in. This allows you to target some SVG defined elsewhere and essentially clone it where you need it. In the end, you still have inline SVG, but it's very succinct:




Information about this:

1) https://css-tricks.com/svg-sprites-use-better-icon-fonts/
2) https://css-tricks.com/svg-symbol-good-choice-icons/

 
Bear Bibeault
Author and ninkuma
Marshal
Posts: 66307
152
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Chris Coyier wrote:The best though, I think, is that SVG has a <use> element baked right in. This allows you to target some SVG defined elsewhere and essentially clone it where you need it. In the end, you still have inline SVG, but it's very succinct:




Information about this:

1) https://css-tricks.com/svg-sprites-use-better-icon-fonts/
2) https://css-tricks.com/svg-symbol-good-choice-icons/


Cool, that's what I've been doing when there are multiple uses -- nice to know I was on the right path (no pun intended) -- but it still felt "wrong" inlining the original SVG. (Perhaps sometimes there's such a thing as "too much" training .)
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!