The CSS :focus-within pseudo-class matches an element if the element or any of its descendants gets focus. [1] The element must be able to receive focus. Form elements can receive focus by default.
Required knowledge:
Syntax
:focus-within {
css declarations;
}
Top tip: Be sure not to allow the changes to “shift” the elements (unless, for some reason, you want the element to change size and potentially shift other elements in doing so).
Focus
We come across the concept of focus in Access and HTML forms.
Forms have controls (text boxes etc). We can click inside these controls and provide information. We can navigate between these controls using the TAB key and the SHIFT + TAB key combination on the keyboard. We can modify this behaviour by changing the tab order.
If you want to make a non-interactive element (like a <div>) focusable, you can add a tabindex attribute with a value of 0 or -1.
Example
Below is a simple example where the background colour of the form will change as soon as one of the controls receives focus through clicking or tabbing. To save you from tabbing all the way through the entire page, click the button to give it focus and then press the TAB key.
References:
- W3Schools.com (no date) W3Schools Online Web Tutorials. Available at: https://www.w3schools.com/cssref/sel_focus-within.php (Accessed: 20 May 2025).