我有一个网站,它使用
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>
使背景图像易于访问的最语义化方法是同时使用背景图像和常规
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>
编辑: object-fit 属性消除了对背景图像的需要,但在撰写本文时,IE 或 Edge 不完全支持此属性。
W3C 为此上下文提供了一个示例,只需为 div 提供一个
role="img"
并在您的描述中提供 aria-label
即可。
这意味着他们需要替代文本才能被屏幕阅读器和其他辅助技术访问。
您完全正确地指出,用户可能会使用非屏幕阅读器的辅助技术。此外,任何使用
sr-only
CSS 类的方法都不得用作确保每个用户都可以访问文本信息的唯一方法。
例如,视力不佳的人可能希望丢弃所有看起来模糊的图像并显示其替代文本。
object-fit
属性适用于自Edge 16以来的图像,因此对于92%的浏览器来说不再是问题,并且可以为旧版浏览器提供后备。