Alternate text for Background Images
Add alternate text to Background Images for accessibility purposes
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.
<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>
<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 🙏