Checkout my CSS Grid By Example and Getting Started With React video courses on Skillshare. Sign up now and get one free month of Skillshare.

CSS using focus-within to highlight active element

We have seen in yesterday's post how to use the focus-within pseudo class to build a pure CSS multi-level dropdown menu.

While researching that article, I've seen an example on CSS Tricks about using focus-within with forms.

And it made me realize that we easily build a multi-step HTML form like like the one in the video below:

Step 1: Building the basic multi-sept HTML form

The first step will be to build the raw unstyled form:

<form>
  <fieldset>
    <h3>Step 1: User data</h3>
    <label>Name:</label><input type="text">
    <label>Email:</label><input type="text">
  </fieldset>
  <fieldset>
    <h3>Step 2: Address</h3>
    <label>Address:</label><input type="text">
    <label>Zip code:</label><input type="text">
  </fieldset>
</form>

Will just add some basic CSS to center the form in the body of the document, and some small tweaks for the fields:

body {
  display: flex;
  min-height: 100vh;
  justify-content: center;
  align-items: center;
}

fieldset {
  display: flex;
  flex-direction: column;
  margin: 1rem;
}

At this point the form will look as below:
screenshot of simple 2 steps form

Step 2: Using focus-within to change the background color of the active element

As a quick recap of how focus-within works: the :focus-within selects an element if that element contains any children that are focused.

Based on this we can easily add a specific background to the active set in the form:

fieldset {
  /* extra properties here */
  transition: background 1s ease;
}

fieldset:focus-within {
  background: yellow;
}

And that extra CSS will produce the below result:
screenshot of html muti step form where the current step has a yellow background added with focus-within

Step 3: Using focus-within to highlight the active element with a modal effect

The really interesting part is what we can do if we combine a box-shadow with the :focus-within pseudo class. Using them we can get a lightbox style effect:

fieldset {
   /* extra properties here */
  box-shadow: 0 0 0 100vmax rgba(0, 0, 0, 0);
}

fieldset:focus-within {
  background: yellow;
  box-shadow: 0 0 0 100vmax rgba(0, 0, 0, 0.8);
}

The above code will produce this effect for each step in the form:
screenshot of html form with fieldset highlited by focus-within

You can see the full codepen here.

More examples of focus-within

A few more examples of what we can do with this pseudo class:

Also, speaking of pseudo classes checkout this tutorial on how we can use the CSS link :target to style elements.

Home Screencasts Best of Newsletter Search X