如何将alt文本添加到背景图像?使背景图像可访问

时间:2018-02-21 19:17:02

标签: html css accessibility

我有一个网站使用background-size: cover将其许多图片显示为背景图片,以确定其大小以完全填充元素,同时裁剪图像中不适合的任何部分。

问题在于这些图像并非纯粹的装饰性。它们是页面信息内容的重要组成部分。这意味着他们需要alt文本才能供屏幕阅读器和其他辅助技术使用。

alt描述添加到背景图像的最具语义的方法是什么?



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;
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

<article class="panel panel-default">
  <header class="panel-heading">
    <h4 class="panel-title">Title of Article</h4>
  </header>
  <div class="panel-body">
    <figure class="article-image"></figure>
  </div>
  <footer class="panel-footer">
    <a class="btn btn-default" href="#">Read</a>
  </footer>
</article>
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:10)

使背景图像可访问的最具语义的方法是同时使用背景图像和常规img标记。

  1. img放置在带背景图片的元素中。
  2. 直观隐藏img,以便有视力的用户只看到其背后的背景图片,但使用辅助技术的用户仍会看到img
  3. 注意:只需将图片设置为display: none;,也会将其隐藏在辅助技术之外,这不是目标。需要采用不同的方法。

    如果您正在使用Bootstrap,它有一个方便的内置类来执行此操作:.sr-only。如果您不是,则可以将该类的样式添加到您自己的样式表中:

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

    将此技术应用于上面的示例如下所示:

    &#13;
    &#13;
    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;
    }
    &#13;
    <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
    
    <article class="panel panel-default">
      <header class="panel-heading">
        <h4 class="panel-title">Title of Article</h4>
      </header>
      <div class="panel-body">
        <figure class="article-image">
          <!-- include the img tag but visually hide it with .sr-only -->
          <img class="sr-only" alt="Bill Murray" src="http://www.fillmurray.com/300/300">
        </figure>
      </div>
      <footer class="panel-footer">
        <a class="btn btn-default" href="#">Read</a>
      </footer>
    </article>
    &#13;
    &#13;
    &#13;

    编辑 object-fit property消除了对背景图片的需求,但在撰写本文时,IE或Edge并未完全支持此属性。

答案 1 :(得分:3)

W3C为此提供了一个示例,只需向div提供一个role="img",并在您的描述中提供一个aria-label

更多信息在这里:http://mars.dequecloud.com/demo/ImgRole.htm

答案 2 :(得分:1)

  

这意味着他们需要替代文字,以便屏幕阅读器和其他辅助技术可以访问。

您完全正确地指出,用户可能会使用非屏幕阅读器的辅助技术。此外,任何使用sr-only CSS类的方法都不能用作确保每个用户都可以访问文本信息的唯一方法。

例如,低视力的人可能想要丢弃所有看似模糊的图像并显示其文字替代品。

The object-fit property works for images since Edge 16所以92%的浏览器不再是问题,a fallback can be provided for older browsers.

相关问题