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:
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:
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:
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:
- Solved with CSS! Dropdown Menus
- the article that inspired this one link
- The CSS :focus-within Pseudo-Class article on digital ocean
- my initial example with focus-within and a pure CSS dropdown menu
Also, speaking of pseudo classes checkout this tutorial on how we can use the CSS link :target to style elements.
📖 50 Javascript, React and NextJs Projects
Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.
📖 50 Javascript, React and NextJs Projects
Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.