CSS :focus-within

css
Published on February 19, 2019

The :focus-within pseudo-class is a selector for an element that contains a focused element as a child. So whenever a child becomes focused, the :focus-within selector is applied to the parent.

The :focus-within CSS is also triggered when the element is in focus, working just like the :focus selector in this case.

A simple example would be a case of a form. Whenever a user focuses on a text field in it, specific CSS can be applied to the form through :focus-within.

Demo

Whenever we focus on a textbox, the background color of the complete form changes. If only :focus pseudo-class was used, only the CSS of the textboxes could have changed. But with :focus-within, the parent container can also be reached.

Below is the associated HTML & CSS for the above demo :

<form class="demo-form">
	<input type="text" placeholder="Name" />
	<input type="text" placeholder="Email" />
</form>
.demo-form {
	background-color: #bdc3c7;
	padding: 20px;
}

.demo-form:focus-within {
	background-color: #f1c40f;
}

.demo-form input[type="text"]:focus {
	border: 1px solid #d35400;
}

Using :focus-within to Remove Unnecessary Javascript Code

Before :focus-within, there was no way to reach the parent container from a child. This makes :focus-within pretty useful, specially while handling onfocus and onblur Javascript events. Who wouldn't like to replace Javascript code with only CSS ?

This is explained through a simple example below — whenever a textbox is focused, a tooltip comes up. We will first handle this using the conventional way of onfocus / onblur events. Next we will see how this can be achieved with pure CSS.

Using Javascript :

* Must be a valid email

HTML, CSS & Javascript codes :

<div class="form-container">
	<input type="text" class="email" placeholder="Enter email" />
	<div class="tooltip">* Must be a valid email</div>
</div>
.tooltip {
	display: none;
}
$(".email").on('focus', function() {
	$(".tooltip").show();
});

$(".email").on('blur', function() {
	$(".tooltip").hide();
});

Using CSS :

* Must be a valid email

HTML & CSS :

<div class="form-container-2">
	<input type="text" class="email-2" placeholder="Enter email" />
	<div class="tooltip-2">* Must be a valid email</div>
</div>
.tooltip-2 {
	display: none;
}

.form-container-2:focus-within .tooltip-2 {
	display: block;
}

The CSS method is obviously much more optimized. Using :focus-within, we have managed to remove the onfocus / onblur event handlers.

Final Words

Like told earlier, :focus-within is the only CSS selector that reaches a parent from a child. Keep :focus-within in mind while you're coding your application. It may help to optimize your code.

In this Tutorial