👋
Welcome to my blog!

Alternate text for Background Images

Add alternate text to Background Images for accessibility purposes

Alternate text for Background Images
HTML
React
JSX

Published At

5/20/2021

Reading Time

~ 1 min read

For those times when you need to use background-image instead of using img tag because of some design related constraints.

With background image, there is no attribute for alternate text alt. But there is a way to do it.

jsx
<div
  role="img"
  aria-label={article.img.title}
  style={{
    background: `url(${article.img.src})`,
    backgroundPosition: 'center',
    backgroundRepeat: 'no-repeat',
    backgroundSize: 'cover',
  }}
>
  <p className="hidden">{data.frontmatter.title} image</p>
</div>
jsx
<div
  role="img"
  aria-label={article.img.title}
  style={{
    background: `url(${article.img.src})`,
    backgroundPosition: 'center',
    backgroundRepeat: 'no-repeat',
    backgroundSize: 'cover',
  }}
>
  <p className="hidden">{data.frontmatter.title} image</p>
</div>

Here, the trick is using role and aria-label, that is it. We're setting the role of the div to img. And providing the alternate text with the help of aria-label.

🍃

Do you have any questions, or simply wish to contact me privately? Don't hesitate to shoot me a DM on Twitter.

Have a wonderful day.
Abhishek 🙏

Join My Exclusive Newsletter Community

Step into a world where creativity intersects with technology. By subscribing, you'll get a front-row seat to my latest musings, full-stack development resources, and exclusive previews of future posts. Each email is a crafted experience that includes:

  • In-depth looks at my covert projects and musings to ignite your imagination.
  • Handpicked frontend development resources and current explorations, aimed at expanding your developer toolkit.
  • A monthly infusion of inspiration with my personal selection of quotes, books, and music.

Embrace the confluence of words and wonder, curated thoughtfully and sent straight to your inbox.

No fluff. Just the highest caliber of ideas.