Typically, alt text is used with
<img> tags in HTML to provide a textual alternative for images. However, if an image is set as a CSS background, the
alt attribute can't be added directly because CSS does not have a built-in mechanism for this. But one common workaround involves using ARIA roles and properties to improve accessibility.
Here's a brief example:
In the above code,
role="img" informs assistive technologies that the div element should be treated like an image.
aria-label provides the alternative text for the image.
Please note, while this method can improve the accessibility of your site, it isn't as universally supported or effective as using alt text with regular
<img> elements. Whenever possible, use
<img> tags for important content images as it's the most accessible practice. CSS background images are usually used for presentational purposes and thus don't require alt text.
For some cases where you want to use images as backgrounds but also need them to be meaningful for screen readers, you could consider using an empty
<img> tag approach:
This way, you still get the design benefits of a background image, but also provide an alt attribute for screen readers.