loading...
Cover image for Floating Label over input

Floating Label over input

yne profile image Rémy F. Updated on ・1 min read

Thanks to the material guidelines, we all want a floating label on top of our <input>.
A solution is to use, next to the input, a text element that will be the pulled-up label.

<label>
  <input>
  <span>Label</span>
</label>

This <span> shall be raised when the <input> is :focus or when it holds a value, sadly there is no pseudo-class for that.
Possible hacks involves :

  • adding a [required] so the input is :invalid state when empty => bad : it prevent any form submit
  • adding a [placeholder] so the input has a :placeholder-shown state => require an empty placeholder

the default state must be usable.

In case of bad CSS support, we don't want our input to be covered by the span, so we revert the logic in order to pull-down the span in the following case :

The span shall cover the input if the input has an blank placeholder and is neither focus nor filled.

Which give us the following rules:

label>input[placeholder=" "]:not(:focus):placeholder-shown + span {
  transform: translateY(1em) scale(1.25);
}

You will now have a working state (label already pushed up) if :

  • the :placeholder-shown is unsupported.
  • the placeholder is not a space
  • the value is already set by attribute

Posted on by:

yne profile

Rémy F.

@yne

c29ycnkgdG8gZGlzYXBvaW50IHlvdSwgSSBoYWQgbm90aGluZyB0byBzYXkgOy0p

Discussion

markdown guide