Background images with alt tags for accessibility

If you’re front-end developer, chances are that at some point you’ll need to use the css background-image property to display an image that isn’t just for presentational purposes. An example of which might be a full width banner image that resizes responsively. In this scenario, we can use the css background property and set background-size: cover; this scales and crops the image in a way that can’t easily be achieved using the good old html img tag.

If the message or meaning of your image is relevant to your content then you’ll want it to be accessible to all, usually this is achieved by adding an alt attribute to the img tag with a description of the image. We can’t quite do the same thing with our element that has a background image, but we can do something similar that should be interpreted in the same way to screen readers.

The solution that I’ve found is to embed an img with src and alt attribute inside the element with the background image. This indicates to the screen reader that there is an image with a description at that point on the page. To hide the img so that it is only seen by screen readers we add specific styles to it, check out the demo below, it works well on Apple Voiceover, with it reading out the alt tag and even giving a generated description of the image (In this case: Well lit, very blurry).

 

See the Pen background-image and alt tags by davey (@daveybrown) on CodePen.

  • Hi, this is a comment.
    To get started with moderating, editing, and deleting comments, please visit the Comments screen in the dashboard.
    Commenter avatars come from Gravatar.

  • Davey

    Test comment

  • Dmitriy

    Interesting! I’ve been looking for something like that. Question: does it work the same in the screen reader if you lazy-load both images – the background and the img tag? (I think it should). I’m also curious in terms of SEO implications – on one hand this approach is better for SEO due to having a proper img tag, on the other– not sure if opacity: 0 would negate the SEO benefits. Do you have any experience with that, meaning, do you know if Google would index these images?