Grab your user's attention with the :focus-within CSS selector

Vitor Paladini - Oct 30 '20 - - Dev Community

Here's a neat little trick:

You can use the :focus-within selector to style the parent of a focused element.

An example of how on focus overlay works

That allows you to create some interactive form UI without a single line of JavaScript. Try the example below:

This demo uses :focus-within, plus the ::before pseudo-selector and some absolute positioning magic. We'll go through the details but you can check the full source below.

:focus-within selector + ::before pseudo-elements + absolute positioning

All in a single declaration block! Let's have a look at the most important part of this example.

body:focus-within::before {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.7);
}
Enter fullscreen mode Exit fullscreen mode

body:focus-within

This selector will apply styles whenever there is focus... within the body!

Oh, and :focus-within works with any element. We're sticking with body only for this example.

You can be creative and come up with .literallyAnyElement:focus-within and use this selector as you please.

body:focus-within::before + absolute positioning

In our example, that means that whenever any field is focused on the body, a ::before pseudo-element will be created with those styles:

content: "";
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.7);
Enter fullscreen mode Exit fullscreen mode

The content: '' property is required for pseudo-elements and everything else are properties used to create a dark, transparent overlay that fills the whole screen!

Extra stuff to make it work properly

Keep in mind that you still need to make a couple of tweaks to make the overlay work perfectly.

html,
body {
  height: 100vh;
}
Enter fullscreen mode Exit fullscreen mode

This makes sure that the overlay fills the whole screen even if there isn't enough content on the page.

form {
 position: relative;
Enter fullscreen mode Exit fullscreen mode

This position: relative; ensures that the overlay renders below the form.


And that's it for this week's neat little trick. Thanks for reading!

Make sure the check the other tricks in the series and follow me on Twitter if you found any of my articles helpful πŸ˜„


EDIT: Make sure to check Andrew's suggestion in the comments below!


Photo by Stefan Cosma on Unsplash

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player