CSS :placeholder-shown Pseudo-class
The :placeholder-shown pseudo-class represents any <input> or <textarea> element that is currently displaying placeholder text.
1. The Concept
This selector allows you to detect whether a user has typed anything into an input field (assuming the input has a placeholder attribute).
- Placeholder Visible: The user has not typed anything.
- Placeholder Hidden: The user has typed something (or there is a value set).
2. Basic Usage
/* Style the input when it's empty (showing placeholder) */
input:placeholder-shown {
border-color: <a href='/?search=%23ccc' class='obsidian-tag'>#ccc</a>;
}
/* Style the input when it has text (placeholder is hidden) */
input:not(:placeholder-shown) {
border-color: green;
background-color: <a href='/?search=%23e8f5e9' class='obsidian-tag'>#e8f5e9</a>;
}
Note: The input must have a placeholder attribute for this to work, even if it's just a space (placeholder=" ").
3. Use Case: Floating Labels
The most popular use case for :placeholder-shown is creating "Floating Labels" (like Material Design) without JavaScript.
HTML:
<div class="input-group">
<input type="text" id="name" placeholder=" " required>
<label for="name">Name</label>
</div>
CSS:
.input-group {
position: relative;
padding-top: 10px;
}
input {
padding: 10px;
width: 100%;
}
label {
position: absolute;
left: 10px;
top: 20px; /* Initial position (inside input) */
transition: 0.2s;
pointer-events: none; /* Allow clicking through to input */
color: #999;
}
/* Move label up when input is focused OR has content */
input:focus + label,
input:not(:placeholder-shown) + label {
top: 0;
font-size: 0.8em;
color: blue;
}
4. Browser Support
:placeholder-shown is supported in all modern browsers.
programming/css/css programming/css/pseudo-classes-and-pseudo-elements programming/css/selectors