CSS Animation Example: Floating Label
The "Floating Label" is a popular pattern for form inputs where the placeholder text smoothly transitions into a label when the user focuses on the field or enters text.
This effect utilizes the ~ (general sibling combinator) and the :placeholder-shown pseudo-class. We animate the top and font-size properties of the label using a transition when the input receives :focus or is no longer showing its placeholder (meaning it has content).
placeholder=" " (a single space) to the HTML input element is required for the :placeholder-shown CSS selector to function correctly as a state-tracker for "is empty".
Here is the code to create the Floating Label animation.
Accessibility Considerations
As always, provide a static version of the layout for users who prefer reduced motion. We can use the prefers-reduced-motion media query to detect if the user has requested that their system minimize non-essential motion. Users generally set this preference via their operating system settings or a browser extension.
Here we quickly disable the transition so the label snaps instantly into place.
@media (prefers-reduced-motion: reduce) {
.floating-input, .floating-label {
transition: none;
}
}