HTML, React, JSX

Alternate text for Background Images

Add alternate text to Background Images for accessibility purposes
A corgi smiling happily

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.

2 role="img"
3 aria-label={article.img.title}
4 style={{
5 background: `url(${article.img.src})`,
6 backgroundPosition: 'center',
7 backgroundRepeat: 'no-repeat',
8 backgroundSize: 'cover',
9 }}
11 <p className="hidden">{data.frontmatter.title} image</p>

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 🙏

Subscribe to my newsletter

Get email from me about my ideas, full-stack development resources, tricks and tips as well as exclusive previews of upcoming articles.

No spam. Just the highest quality ideas you’ll find on the web.