Label floats up when the field is filled or focused: :placeholder-shown + :focus + sibling selector, zero JS. The one-space placeholder trick. Type & see. An…
Why it matters
A lot of form UI that looks like it needs JavaScript only needs pseudo-classes. Knowing why the HTML puts the input before the label, and why the placeholder must be one space, keeps the trick from breaking in someone else’s hands, and a real <label> keeps the field named for screen readers.
The key idea
Two pseudo-classes, one combinator, no JS
Common mistakes
The field is filled and blurred, and the label drops onto the text Only :focus lifts the label, and focus goes on blur. Add a "filled" signal: input:not(:placeholder-shown) + label, with placeholder=" " on the input. (With no placeholder at all, the opposite happens: the label stays up and never comes down.)
Dropping the <label> and relying on the placeholder for the field’s name A placeholder disappears once you type, is often too pale, and is only used as the accessible name when there is nothing else. Still write a real <label for>; a floating label shows exactly that.
The label is placed before the input, and never floats The + (and ~) combinator only reaches a sibling AFTER. Write the input first and the label after it, or use .field:has(input:focus) label, which does not care about order.
Try it in this playground
Type in the real slip The first character makes :placeholder-shown stop matching, and the label floats. Delete it all: it comes down again (when not focused).
Click the empty slip, do not type The label still floats because of :focus. Click away: it comes down again.
Pick "Only :focus", then "No placeholder" Two opposite ways to break it: in the first the label covers the text after blur, in the second the label stays up. See the samples on the table.
Pick "The :has() version" The label comes before the input, and it still works: .field:has(input:focus) label asks from the parent, not from the sibling in front of it.