Explain Codes LogoExplain Codes Logo

Do I use , , or `` for SVG files?

html
responsive-design
svg
fallback
Anton ShumikhinbyAnton Shumikhin·Nov 9, 2024
TLDR

Embedding SVGs falls in a simple rule: simpler uses call for <img>, guaranteeing SEO boost and quick performance. Check this quickie:

<!-- SVG in the house --> <img src="image.svg" alt="Just a very cool SVG image">

For dynamic interaction or scripting, switch to <object>. It maintains a more interactive HTML layer:

<!-- SVG on steroids --> <object type="image/svg+xml" data="image.svg"></object>

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>:
    <!-- SVG with a plan B --> <object type="image/svg+xml" data="your.svg"> <img src="yourfallback.jpg" alt="Oops! No SVG here."> </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 the getSVGDocument().
  • 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:

<!-- A very responsive SVG --> <img src="image.svg" alt="Description" srcset="image.svg 1x, [email protected] 2x">

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.