Explain Codes LogoExplain Codes Logo

Css background image alt attribute

html
responsive-design
accessibility
seo
Anton ShumikhinbyAnton Shumikhin·Oct 8, 2024
TLDR

CSS backgrounds don't support alt text like the <img> tags. For accessibility, use aria-label:

<div style="background:url('image.jpg');" aria-label="Image description"></div>

This provides a text description for assistive technologies and none is shown visually. Quite the ninja move, isn't it?

Too long; didn't read (TL;DR)

You can't use alt on CSS backgrounds. But hey, we have workarounds:

  1. ARIA to the rescue.
  2. <img> with alt, when the image says more than a thousand words.
  3. title attribute, because who doesn't love good tooltips?
  4. Hide an <img> like you're playing hide and seek.

Where, Why and How: alt attribute and CSS backgrounds

Where's alt in CSS backgrounds? Nowhere! Why? CSS backgrounds serve a pure aesthetic purpose, they're the frosting on your website cake, hence no alt here.

How can we workaround this? Let's explore further.

ARIA and img: Your new best friends

ARIA roles and alt attribute in img come in handy if you still need to provide accessible text for background images.

<!-- Here's ARIA being your knight in shining armor --> <div style="background:url('icon.png');" role="img" aria-label="Icon description"></div>
<!-- `img` tag for when it's more than just a pretty picture --> <img src="critical-image.jpg" alt="Brief description of the image">

Title, Hidden <img>, Decorative or Content?

Your image could be just decoration or vital content. If it's only for the vibe,CSS background wins. If it's for the meaning, embrace the <img> with alt.

Consider title for tooltip and hidden <img>, as an invisible hero, providing alt descriptions off-screen.

SEO and Performance Optimizations

SEO loves <img> and alt like cookies and cream. For CSS backgrounds, we can:

  • Sneak in hidden <img> with alt
  • Nail textual representation for accessibility

Remember to keep performance in mind for lightning-fast load times.

ARIA best practices and the importance of IMG

  • Don't overuse ARIA. Add it where native HTML doesn't suffice.
  • Always provide fallbacks for background images. Hint: <img> tags.
  • Label your images loud and clear. Accessibility loves descriptions.