CSS :focus-within

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.

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 parent has keyboard focus!

Consider the following HTML template with default CSS styling:

<ul id="sports">
      <input type="checkbox" name="sports[]">
      <button class="remove">Remove</button>
    <!-- ... -->
#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:

#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.

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!

The post CSS :focus-within appeared first on David Walsh Blog.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.