:placeholder-shown CSS Pseudo Class

Description

The :placeholder-shown pseudo-class is a CSS selector used to target an input element when its placeholder text is being displayed. This pseudo-class is particularly useful for styling input fields in forms when the placeholder text is visible, providing designers with greater control over the appearance of input elements during user interaction.

Here's a brief explanation of how it works:
When an input element has a placeholder attribute and the user hasn't entered any text, the placeholder text is displayed inside the input field. At this point, the :placeholder-shown pseudo-class can be applied to target that input element. This allows you to define styles specifically for the input when it's in this state.

For example, you can use :placeholder-shown to change the color or opacity of the placeholder text, adjust the background color of the input field, or modify its border styles to create a visual effect when the user interacts with the form.

Here's a simple example of how you might use :placeholder-shown in CSS:

input:placeholder-shown {
color: #999; /* Change placeholder text color when it's shown */
background-color: #f2f2f2; /* Adjust background color */
border: 1px solid #ccc; /* Modify the border style */
}

In this example, the input field will have different styles when the placeholder text is visible, and these styles will change as soon as the user starts typing in the input field, causing the placeholder to disappear.

Syntax

:placeholder-shown {
  /* ... */
}

Example

<form>
<label for="name">Full Name:</label>
<input name="name" type="text" />

<label for="email">Email Address:</label>
<input name="email" type="email" placeholder="name@example.com" />

<label for="age">Your age:</label>
<input name="age" type="number" value="18" placeholder="You must be 18+" />
</form>
label {
display: block;
margin-top: 1em;
}

input:placeholder-shown {
background-color: ivory;
border: 2px solid darkorange;
border-radius: 5px;
}

Browser Support

The following table will show you the current browser support for the CSS :placeholder-shown pseudo class.

Desktop
Edge Chrome Firefox Opera Safari
794751349
Tablets / Mobile
Chrome Firefox Opera Safari Samsung Webview
4751349547

Last updated by CSSPortal on: 1st October 2023