Here’s a Neat Trick Using the :Focus Pseudo-Class

Here's a Neat Trick Using the Focus Pseudo-Class


This post will take 1 minute to read.

I love to play around with CSS. So much so that if I have a spare five minutes, I will often open up CodePen and experiment. Doing exactly this the other day, I discovered a couple of things. The first of which was a neat interaction using the :focus pseudo-class, and the second being a line-height issue when working with inputs. You can read about that here.

The fun bit

What I’m doing in the demo is something very similar to the checkbox hack, except instead of using the :checked pseudo-class, I’m using the :focus pseudo-class. This is pretty handy, as :focus has better browser support than :checked.

Using the following markup, I pair the label and input (i.e. clicking the label focuses the input):

<input id="search" type="search">
<label for="search">Search</label>

I then set the width of the input to 0, and increase it again on focus. For example:

input:focus {
    width: 18em;

I take the styling a little further in the demo to give a nice ‘slide to reveal’ effect.

Be sensible

As with anything, use this trick appropriately. There is a fair bit you could use it for, modal images for instance, but just because you can, doesn’t mean you should!

Tweet this


  1. Mike King

    I love the animation effect in your example, very clean dude!

    However in regards to forms, I do think this effect might have some usability issues, namely clicking the “search button” when the input is expanded collapses the input, rather than submitting the text. I’m sure you could hack around this with javascript, but I think it’s worth pointing out.

    Anyway’s, keep up the great work!

  2. Josh

    Thanks, Mike. That’s a great point, and one I neglected to discuss. You are absolutely right; usability is more important than any cool interactions.