Michael Gearon

CSS :focus-within pseduo-class

Michael Gearon

Last updated on

CSS3 Pseudo Element

The :focus-within pseudo-class is a CSS Level 4 selector that is supported by Firefox, Chrome, Safari as well as other browsers apart from Internet Explorer and Edge 18 or less.

Using :hover to display additional information or elements is a very useful technique but the downside to using the hover pseudo-class is that it’s 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:

HTML

 

:focus-within CSS selector

 

Try typing into this form.

 

 

 

 

 

 

CSS


form {
border: 1px solid;
color: gray;
padding: 2rem;
}

form:focus-within {
background: #ffbf47;
color: black;
}

input {
margin: 4px;
}

Example of using the pseudo-class

In the example below you can see the result, if of course you’re using a supported browser. Try clicking into the inputs and notice the container element background colour change to a yellow colour.

See the Pen
:focus-within CSS selector level 4
by Michael Gearon (@michaelgearon)
on CodePen.


To be able to use the :focus-within property, you’ll have to make sure that the inner elements of the container are focusable. Elements like the input and textarea are focusable by default, however img, p or div elements are not.

If you want to make an element focusable then you can use the tabindex attribute to make an element focusable.

Does focus-within work for IE?

The focus-within does not work for IE or Edge. It will be supported in Edge version 76 and onwards.

Removing redundant Javascript code using the :focus-within

As mentioned at the start the :focus-within property allows for better accessibility but also it provides a way to remove redundant JavaScript. Before this property the only real way to achieve this effect would be through Javascript events like the onfocus and onblur.

Summary

There are some great benefits to using the :focus-within property, better accessibility, lighter and cleaner code. Although not supported in IE and some Edge browsers it can help enhance the experience for your users.

Michael Gearon

Written by

Michael Gearon

Senior Interaction Designer and Co-Author to Tiny CSS Projects