CSS Element:placeholder-shown
The :placeholder-shown
pseudo-class in CSS is used to style input fields that display placeholder text. This can be particularly useful when you want to create a distinct appearance for an input field when it is empty (showing the placeholder) versus when it contains user-inputted data.
In this tutorial, we will go through an example using a text input field. We'll create styles that apply only when the placeholder is visible.
<style>
input {
padding: 10px;
font-size: 16px;
border: 1px solid #ccc;
border-radius: 4px;
}
input:placeholder-shown {
background-color: #f9f9f9; /* Light grey background */
color: #999; /* Light grey text */
}
input:not(:placeholder-shown) {
background-color: #fff; /* White background when filled */
color: #333; /* Dark text when filled */
}
</style>
In the example above, when the text input field is empty and displaying the placeholder text 'Enter your name'
, it will have a light grey background and the text will also be in light grey.
When a user starts typing their name in the input field, the :placeholder-shown
style is no longer applied, and the background changes to white with dark text.
Feel free to copy the styles and experiment with different colors and properties to see how :placeholder-shown
can help you enhance the user interface of your forms!