How to add alt text to background images? Making background images accessible

前端 未结 3 749
迷失自我
迷失自我 2021-01-22 08:38

I have a site that is displaying many of its images as background images using background-size: cover to size them to completely fill the element while cropping off

3条回答
  •  天涯浪人
    2021-01-22 09:24

    The most semantic way to make a background image accessible is to use both a background image and a regular img tag as well.

    1. Place the img within the element with the background image.
    2. Visually hide the img so that sighted users just see the background image behind it, but users with assistive technologies are still presented the img.

    Note: just setting the image to display: none; will hide also it from assistive technologies, which isn't the goal. A different approach is needed.

    If you're using Bootstrap, it has a handy built-in class for doing just this: .sr-only. If you're not, you can add the styles for that class to your own stylesheet:

    .sr-only {
      position: absolute;
      width: 1px;
      height: 1px;
      padding: 0;
      margin: -1px;
      overflow: hidden;
      clip: rect(0, 0, 0, 0);
      border: 0;
    }
    

    Applying this technique to the example above looks like this:

    article {
      position: relative;
      width: 320px;
      margin: 5rem auto;
    }
    
    figure {
      width: 100%;
      height: 180px;
      /* not accessible */
      background-image: url('http://www.fillmurray.com/300/300');
      background-size: cover;
      background-position: center;
    }
    
    
    

    Title of Article

    Bill Murray

    Edit: The object-fit property eliminates the need for the background image, but at the time of writing this property is not fully supported in IE or Edge.

提交回复
热议问题