Do I use ,
, or `` for SVG files?
⚡TLDR
Embedding SVGs falls in a simple rule: simpler uses call for <img>
, guaranteeing SEO boost and quick performance. Check this quickie:
For dynamic interaction or scripting, switch to <object>
. It maintains a more interactive HTML layer:
So, <img>
for simplicity, <object>
for superpowers.
What's the best time for SVG tags?
<img>
for the simple life
Employ <img>
for straightforward cases:
- Static SVG images with no interaction needed.
- Responsive design using
srcset
for different resolutions.
<object>
for the marvels of interaction
The <object>
tag is perfect for more complex situations:
- Interactive SVGs, offering access to scripting.
- Fallback content by nesting an
<img>
inside<object>
:
<embed>
for rare usage
- Fits for legacy browsers requiring SVGs.
- Can but rarely used in modern web.
How to play with SVG Internally and Styles?
SVG Manipulation
- To access SVG's inner DOM in
<object>
, pull thegetSVGDocument()
. - Add event listeners from outer document for real-time scaling.
SVG Styling with CSS
- Try
fill
property in CSS to play with SVG colors. - Don't forget same-origin rule applies on embedded styles and scripts.
How to be Responsive and give a Fallback?
Fallback and Accessibility
- Employ PNG fallback for the SVG-shy browsers using
onerror
. - Keep an
alt
description for invisible accessibility heroes.
Responsive Design with srcset
Use srcset
in <img>
for multiple resolution options:
Strategies for Legacy and Compatibility
And What About Older Android Versions?
Know your battles. Android 2.3 gets all zen with multiple backgrounds, but not SVG in CSS.
A Safe Compatibility Check
- Modernizr is your friend to detect SVG support and pre-set fallbacks.
- caniuse.com is your loyal library for real-time compatibility data.
Linked
Linked
Was this article helpful?