Last Updated: February 25, 2016
· hennson

CSS-only: Highlight label when focusing an input field

An adjacent selector matches an element immediately followed by the next element (E + F). If we use the common form element order - label followed by input - we're already stuck. Ok, let's turn them around. But then there is a new problem! Yes, visually the label follows after the actual input field. If you would like to have it back above the text input we need to (visually) switch the positions of the controls again. This can be done via a CSS pseudo-table.

<div class="pseudo-table">
   <input id="yourname" name="yourname" type="text" placeholder="Name...">
   <label for="yourname">Name</label>

The style for the artifical table is...

.pseudo-table { display: table;  }

With this in place we could transform the label e.g. to a table-header-group:

label { display: table-header-group; }

and the input field to a table-row-group:

input { display: table-row-group; }

In combination with our adjacent selector we're done and it looks right:

input:focus + label { color:red; font-weight: bold; }

So no jQuery script required to master this task.

For a demo please see this Fiddle


Say Thanks