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

Sea*_*ean 1 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;
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

Sea*_*ean 10

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

  1. img元素放在背景图像中.
  2. 视觉隐藏,img以便有视力的用户只看到它背后的背景图像,但仍然提供具有辅助技术的用户img.

注意:只是将图像设置为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;
}
Run Code Online (Sandbox Code Playgroud)

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

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;
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

编辑:对象的配合属性消除了背景图像的需要,但在写此属性的时间不完全在IE或边缘支持.

  • 我想我不明白这里的重点。设计上无法访问背景图像。这里真正的问题是您错误地将背景图像用作常规图像。既然你已经实现了一个合适的 `img` 元素,为什么不直接删除背景图片属性呢?我不明白将它保留在 CSS 中有什么价值。 (2认同)
  • @Josh使用背景图片可以利用`background-size:[cover | 包含]`,用于按比例调整任何图像的大小以填充或放入容器中。这是在不使用JavaScript的情况下以非易碎的方式实现影响的唯一方法-用户可能已将其禁用。 (2认同)

小智 6

W3C 为这种上下文提供了一个示例,只需向role="img"div提供一个aria-label提供您的描述。

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