CSS :target pseudo-class used to create simple CSS-only wizard

Radek Anuszewski
2 min readJun 3, 2016

--

:target pseudo-class is applied to element pointed by clicked anchor in href attribute, it has fun use-cases like simple CSS-only wizard. It is less-known feature especially for people which are not a designers, but can be very handy.

CSS :target pseudo-class

If we have element like <div id=”main”>Content…</div>, we can point to it in anchor href attribute, like <a href=”#main”>Scroll to main content</a>. When this href is clicked, our div will have :target pseudo-class applied. It allows us to do few fun things, like CSS-only modal window, or styling paragraph’s headers which users are supposed to read. We can also set display property — and do all other things.

CSS-only very simple wizard

So, if it is possible to show and display elements with :target pseudo-class, it is possible to make simple wizard on these assumptions:

  1. Every displayed step is div with unique id
  2. Every step has anchors which point to previous and next page (except first which has next anchor and last, which has previous anchor)
  3. Targets of this anchors point to ids
  4. With CSS, steps without :target pseudo-class are hidden, and with :target are displayed

So, first and second page might look like this:

<div id=”first”>
<h2>First page</h2>
<a href=”#second”>Open second page</a>
</div>
<div id=”second”>
<a href=”#first”>Back to first page</a>
<h2>Second page</h2>
<a href=”#third”>Open third page</a>
</div>

And it can be a CSS stylesheet for these:

#first {
display: none;
}
#first:target {
display: block
}
#second {
display: none;
}
#second:target {
display: block;
}
#third {
display: none;
}
#third:target {
display: block;
}

Of course, in this very simple implementation we need additional button which displays first page:

<a href=”#first”>Start from first page</a>

Implementation of CSS-only wizard with :target pseudo-class

Here’s final implementation, with additional Bootstrap classes: CSSDesk — CSS target pseudo class used to create simple wizard.

Conclusion

If we only need part of functionality of widget like Wizard, in example it has no logic and it’s only for displaying purposes, maybe we do not need to use plugin and we can do it with pure CSS or JavaScript. It means less dependencies to maintain, less API to learn and (but it’s not really important I think) little bit faster page loading time.

--

--

Radek Anuszewski

Software developer, frontend developer in AltConnect.pl, mostly playing with ReactJS, AngularJS and, recently, BackboneJS / MarionetteJS.