The CSS4 :focus-within selector is explained with examples

The CSS4 :focus-within selector is an exciting CSS level 4 selector. It is a pseudo class ( like nth-child) that represents an element that receives focus or it has a child element that receives focus. It actually asks the browser to apply a style to a parent when any of its children are in focus.

Also it could be used in dropdown menus when we do not want to lose focus or in tables or in forms when user focuses on its inputs. Or simply any element that has children and needs its focus to be taken care of. We will take a look at some examples.

:focus-within selector in forms

While a user filling up a form it would be great if the form style could be changed so that they don’t lose focus and concentrate on the task. Check this pen:


Once you click on one of the inputs ( meaning a form child element), form’s background and colour style is changing:

form:focus-within {
background: #ccc;
color: black;

:focus-within selector in tables

A really good example of using :focus-within pseudo class is inside tables. Whenever you hover over a row of a cell, the whole row’s style could be changed to show the user focus. Check out this pen:

And we used :focus-within for the rows as below:

tbody tr:focus-within,
tbody tr:hover {
background: blue;

:focus-within selector in dropdown menu

I use the example in CSS tricks here and explain the important part of it. This is the example in CodePen:

In the menu adding role=”navigation”  **helps on web accessibility. Also The **aria-label **attribute is used to define a string that labels the current element. We use **aria-label=”submenu” in the dropdown to make it more accessible.

However in order for a navigation bar to be accessible, one should be able to tab through it and focus on the proper item in a sensible order. Additionally to have a screen reader accurately read out loud what is being focused on.

Using :focus-within selector we can achieve these:

ul li:hover > ul,,ul li:focus-within > ul`` {
visibility: visible;
opacity: 1;
display: block;

This way when we tab to the second item, our submenu pops up. As we tab through the submenu, the visibility remains! We then append our code to include :focus **states alongside **:hover to give keyboard users the same experience as our mouse users:

ul li:hover > ul,
ul li:focus-within > ul,
ul li ul:hover,
ul li ul:focus {
visibility: visible;
opacity: 1;
display: block;

There are also other use cases of :focus-within that you could read about in this link for divs and a comprehensive article on dropdown menus here as well. Thanks for reading.

© 2019
Azadeh Faramarzi

This site is created and maintined by Azadeh Faramarzi , A passionate developer, sport and code lover who loves to share and write when she has some time.