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 exper­i­ment. Doing exactly this the oth­er day, I dis­covered a couple of things. The first of which was a neat inter­ac­tion using the :focus pseudo-class, and the second being a line-height issue when work­ing with inputs. You can read about that here.

The fun bit

What I’m doing in the demo is some­thing very sim­il­ar to the check­box hack, except instead of using the :checked pseudo-class, I’m using the :focus pseudo-class. This is pretty handy, as :focus has bet­ter browser sup­port than :checked.

Using the fol­low­ing markup, I pair the label and input (i.e. click­ing 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 styl­ing a little fur­ther in the demo to give a nice ‘slide to reveal’ effect.

Be sensible

As with any­thing, use this trick appro­pri­ately. There is a fair bit you could use it for, mod­al images for instance, but just because you can, does­n’t mean you should!

Tweet this


  1. Mike King

    I love the anim­a­tion effect in your example, very clean dude! 

    However in regards to forms, I do think this effect might have some usab­il­ity issues, namely click­ing the “search but­ton” when the input is expan­ded col­lapses the input, rather than sub­mit­ting the text. I’m sure you could hack around this with javas­cript, but I think it’s worth point­ing out.

    Anyway’s, keep up the great work!

  2. Josh

    Thanks, Mike. That’s a great point, and one I neg­lected to dis­cuss. You are abso­lutely right; usab­il­ity is more import­ant than any cool interactions.