我有一个网站,该站点将其许多图像显示为背景图像,使用background-size: cover
将其大小尺寸,以完全填充元素,同时裁剪不适合的任何部分。<<<<<<<</p>
问题是这些图像不是纯粹的装饰。它们是页面信息内容的关键部分。这意味着他们需要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>
使背景图像访问的最语义方法是使用背景图像和常规img
标签。
- 将
img
放在带有背景图像的元素中。 - 在视觉上隐藏
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;
}
将此技术应用于上面的示例,如下所示:
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">
<!-- 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>
编辑:对象拟合属性消除了对背景图像的需求,但是在编写此属性时,IE或EDGE并未完全支持。
W3C为此提供了一个景象,只需向DIV提供role="img"
,并带有您的描述。
更多信息:http://mars.dequecloud.com/demo/imgrole.htm
这意味着他们需要Alt文本才能访问屏幕阅读器和其他辅助技术。
您完全正确地指出,用户可以使用不是屏幕阅读器的辅助技术。另外,任何使用sr-only
CSS类的方法都不得用作确保可以访问每个用户的文本信息的唯一方法。
例如,视力低下的人可能想丢弃所有会显得模糊的图像并显示其文本替代方案。
object-fit
自从Edge 16以来,CC_13适用于图像,因此对于92%的浏览器而言,它不再是问题,并且可以为较旧的浏览器提供后备。