Tailwind CSS - 屏幕阅读器
Tailwind CSS - 屏幕阅读器工具类
Section titled “Tailwind CSS - 屏幕阅读器工具类”可访问性(a11y)并非事后考虑,它是构建包容性网络体验的必备条件。Tailwind 提供了屏幕阅读器工具类,可以在视觉上隐藏内容,同时仍确保其对屏幕阅读器用户可访问,这是改进 a11y 的常见技术。
核心屏幕阅读器工具类
Section titled “核心屏幕阅读器工具类”这两个工具类是 Tailwind 中可访问性增强的基础。
| 类名 | CSS 属性 |
|---|---|
| sr-only | position: absolute;\nwidth: 1px;\nheight: 1px;\npadding: 0;\nmargin: -1px;\noverflow: hidden;\nclip: rect(0, 0, 0, 0);\nwhite-space: nowrap;\nborder-width: 0; |
| not-sr-only | position: static;\nwidth: auto;\nheight: auto;\npadding: 0;\nmargin: 0;\noverflow: visible;\nclip: auto;\nwhite-space: normal; |
sr-only:将元素从可视区域隐藏,但对屏幕阅读器保持可访问。它是旧式text-indent: -9999pxhack 的现代等效方案,但更加健壮。not-sr-only:恢复sr-only的样式,使元素再次在视觉上可见。当与focus:等状态修饰符结合使用时,它非常强大。
a11y 的实际应用场景
Section titled “a11y 的实际应用场景”除了简单地隐藏元素,我们来看看 sr-only 在实际场景中如何使用,以使 UI (用户界面) 更具可访问性。
用例 1:为图标按钮添加标签
Section titled “用例 1:为图标按钮添加标签”纯图标按钮在视觉上简洁,但如果没有标签,则无法访问。使用 sr-only 为屏幕阅读器用户提供描述性文本标签。
<!DOCTYPE html><html lang="en"><head> <script src="https://cdn.tailwindcss.com"></script></head><body class="p-8 flex justify-center"> <button class="bg-blue-500 hover:bg-blue-700 text-white font-bold p-3 rounded-full"> <svg class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor"> <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6" /> </svg> <span class="sr-only">添加新项目</span> </button></body></html>用例 2:可访问的“跳过内容”链接
Section titled “用例 2:可访问的“跳过内容”链接”“跳过链接”允许键盘和屏幕阅读器用户绕过导航,直接跳转到主要内容。它应该在获得焦点之前是视觉上隐藏的。
<!DOCTYPE html><html lang="en"><head> <script src="https://cdn.tailwindcss.com"></script></head><body> <a href="#main-content" class="sr-only focus:not-sr-only focus:absolute focus:top-4 focus:left-4 z-50 bg-white dark:bg-black text-black dark:text-white p-3 rounded-lg shadow-md"> 跳到主要内容 </a> <header class="p-4 bg-gray-200"> <!-- 你的网站导航在此 --> <nav>...</nav> </header> <main id="main-content" class="p-8"> <h1 class="text-2xl font-bold">主要内容</h1> <p>这是页面主要内容开始的地方。</p> </main></body></html>正确使用 sr-only 和 not-sr-only 是一种简单但有效的方式,可以改善网站对所有用户的可用性,包括依赖辅助技术的人。它确保即使在缺少视觉提示的情况下,上下文和功能也能得以保留。