Monthly Archives: February 2014

CSS Only Placeholders Field Labels (i.e. Float Labels)

In a previous post I showed how I made the float labels for Nest’s store, which can make forms with placeholder labels more user friendly.

Click for the live demo
Click for the live demo

One of the glaring problems with the solution was that it required JS to work. Shortly after posting I realized that there was a very simple way to make this work without JavaScript for browsers that support the adjacent sibling selector. All you need to do is put the label after the field and then add a couple lines of CSS. In short

HTML

<span class="field">
   <input type="text" id="fname" name="fname" placeholder="First Name" />
   <label for="fname">First Name</label>
</span>

CSS

.field label {
  display: none;
}
.field input:focus ~ label {
  display: block;
}

This assumes that you have styles already defined for how you want to present the label. See the demo for the full code.

Persisting Labels

If you want to make the float labels persist after the user leaves the field, you can use the CSS3 :valid pseudo class along with the required attribute. When you put a required attribute on a field, the browser will mark it as ‘valid’ if it is not empty. This way we can show the float label when the user has entered something in the field.

Click for the live demo
Click for the live demo

HTML

<span class="field">
   <input type="text" id="fname" name="fname" placeholder="First Name" required />
   <label for="fname">First Name</label>
</span>

CSS

.field label {
  display: none;
}
.field input:focus ~ label,
.field input:valid ~ label {
  display: block;
}

Full Demos

To see both of these in action: