无障碍/SEO 友好的 CSS 隐藏

Avatar of Chris Coyier
Chris Coyier
.screen-reader-text {
  position: absolute;
  top: -9999px;
  left: -9999px;
}

此类可以从页面中移除一个项目,将其移出文档流,并且不会导致溢出滚动。

当目标是隐藏元素的视觉效果但保留其对屏幕阅读器的可访问性时,它比display: none;甚至visibility: hidden;更好。

Snook 有一个关于更强大的类的演练,该类考虑了更多的情况。

.element-invisible {
  position: absolute !important;
  height: 1px; width: 1px; 
  overflow: hidden;
  clip: rect(1px 1px 1px 1px); /* IE6, IE7 */
  clip: rect(1px, 1px, 1px, 1px);
}

WordPress 使用了一个更强大的类,该类考虑了在元素获得焦点时应显示元素。

.screen-reader-text {
  border: 0;
  clip: rect(1px, 1px, 1px, 1px);
  clip-path: inset(50%);
  height: 1px;
  margin: -1px;
  overflow: hidden;
  padding: 0;
  position: absolute;
  width: 1px;
  word-wrap: normal !important;
}
.screen-reader-text:focus {
  background-color: #eee;
  clip: auto !important;
  clip-path: none;
  color: #444;
  display: block;
  font-size: 1em;
  height: auto;
  left: 5px;
  line-height: normal;
  padding: 15px 23px 14px;
  text-decoration: none;
  top: 5px;
  width: auto;
  z-index: 100000; /* Above WP toolbar. */
}