:placeholder-shown for Input States
You'll learn how to style input fields differently based on whether their placeholder text is currently visible.
What Is :placeholder-shown?
The :placeholder-shown pseudo-class targets input or textarea elements when their placeholder is being displayed. This happens when the field is empty and hasn't been filled yet. The moment a user types anything, the placeholder disappears and this selector no longer applies.
Think of it like a "vacancy" sign at a hotel — the sign is only visible when the room (input field) is empty. Once someone checks in (types), the sign turns off.
Why It Matters
This selector is perfect for creating floating label effects without JavaScript. You can style the label differently when the input is empty versus when it contains text, creating a polished, modern form experience.
How It Works
When an input shows its placeholder, :placeholder-shown matches it:
input:placeholder-shown {
border-color: #ccc;
}
/* When NOT showing placeholder (has content) */
input:not(:placeholder-shown) {
border-color: blue;
}
Floating Label Pattern
Combine :placeholder-shown with the adjacent sibling selector to move labels:
input:placeholder-shown + label {
/* Label stays inside field when empty */
transform: translateY(0);
font-size: 1rem;
}
input:not(:placeholder-shown) + label {
/* Label floats up when field has content */
transform: translateY(-1.5rem);
font-size: 0.875rem;
}
This creates that "Material Design" effect where labels elegantly move out of the way as users type.
Important Note
For :placeholder-shown to work, the input must have a placeholder attribute, even if it's empty (placeholder="").
Key Takeaway: The :placeholder-shown pseudo-class lets you style inputs based on whether they're empty, enabling elegant floating labels and conditional formatting without JavaScript.