css焦点
Using :hover
to display additional information or elements is a very useful technique but a big drawback to using the hover pseudo-class is that they are usually not accessibility-friendly. Not everyone uses a mouse and some users have visual impairments, so they rely on screen readers or the keyboard -- two functionality that don't technically hover.
使用:hover
显示其他信息或元素是一种非常有用的技术,但是使用hover伪类的一个很大的缺点是它们通常不便于访问。 并非每个人都使用鼠标,并且某些用户有视觉障碍,因此他们依赖屏幕阅读器或键盘-这两种功能在技术上不会悬停。
Luckily the CSS spec gives us a gift to pair with :hover
: :focus-within
. With :focus-within
developers can modify styles of elements when an element or its children has keyboard focus!
幸运的是,CSS规范为我们提供了与:hover
:focus-within
配对的礼物。 使用:focus-within
,当元素或其子元素具有键盘焦点时,开发人员可以修改元素的样式!
Consider the following HTML template with default CSS styling:
考虑以下具有默认CSS样式HTML模板:
<ul id="sports">
<li>
<label>
<input type="checkbox" name="sports[]">
Soccer
<button class="remove">Remove</button>
</label>
<!-- ... -->
</li>
</ul>
#sports .remove {
display: none;
}
#sports li:hover .remove {
display: inline-block;
}
With the code above, hovering over a list item would show the "remove" button. That's great for mouse users but totally useless for keyboard users. Let's fix that using :focus-within
:
使用上面的代码,将鼠标悬停在列表项上将显示“删除”按钮。 这对鼠标用户来说很棒,但对键盘用户却完全没有用。 让我们使用:focus-within
修复它:
#sports .remove {
display: none;
}
#sports li:hover .remove,
#sports li:focus-within .remove {
display: inline-block;
}
Once focus hits the checkbox, the focus is technically within the list item and thus we can employ :focus-within
to show the "remove" button.
一旦焦点到达复选框,焦点就在列表项内,因此我们可以使用:focus-within
来显示“删除”按钮。
Accessibility is something that gets considered last but shouldn't be an afterthought; in a way, :focus-within
is a useful ally even when accessibility was an afterthought. Even when considering accessibility up front, :focus-within
should be in every developer's toolbox!
可访问性是最后要考虑的事情,但不应该是事后的想法。 从某种意义上说, :focus-within
是有用的盟友,即使可访问性是事后的想法。 即使在考虑可访问性时, :focus-within
应该在每个开发人员的工具箱中!
css焦点