CSS Reference ยท Pseudo-classes
The :placeholder-shown pseudo-class
Reference for the CSS :placeholder-shown pseudo-class: style inputs while their placeholder text is visible, with floating-label examples and browser support.
The :placeholder-shown pseudo-class matches an <input> or <textarea> while its placeholder text is visible. That means the element has a placeholder attribute and its value is currently empty. As soon as the user types a character, the element stops matching.
It is the basis of the "floating label" pattern, and a handy way to style an empty field differently from a filled one, without JavaScript.
input:placeholder-shown { border-style: dashed; }
Try it
The placeholder is a single space, so it is "shown" (and matches) while the field is empty, but the visible text is just the label.
Syntax
:placeholder-shown { /* declarations */ }
No arguments; specificity (0,1,0). It only applies to elements that can have a placeholder: <input> types that accept one (text, email, search, url, tel, password, number) and <textarea>.
Syntax and arguments
| Part | Description |
|---|---|
:placeholder-shown |
Matches a text-like control that has a placeholder attribute and an empty value. |
:not(:placeholder-shown) |
Matches a control that has been given a value, or has no placeholder at all. |
::placeholder |
Not the same thing: a pseudo-element that styles the placeholder text itself. |
Usage notes
- The attribute is required. Without
placeholder, the control never matches. The common trick isplaceholder=" "(one space) when you do not want visible placeholder text. - Label order matters. The sibling combinators
+and~only look forward, so the label must come after the input in the HTML for the floating pattern. Alternatively, wrap both in a container and use:has(). - Don't replace labels with placeholders. A placeholder disappears when typing and has low contrast by default. Always keep a real
<label>; the floating label pattern does this correctly. - Pair it with validity.
:not(:placeholder-shown):invalidstyles a field that has content and is invalid, so you can avoid flagging empty fields. See also:user-invalid. - Pre-filled values. A field the browser autofills or that has a
valueattribute counts as filled, so it does not match.
Browser support
Supported in all current browsers and Baseline widely available.
Related
::placeholderโ the placeholder text itself:autofillโ autofilled inputs:user-invalidโ invalid after interaction- Lessons: Styling forms, Pseudo-classes