:valid CSS Pseudo Class
Description
The :valid
pseudo-class in CSS is used to target form elements that have passed validation according to their defined constraints or rules. This pseudo-class is often applied to input fields, such as text inputs, email inputs, or number inputs, within HTML forms that utilize attributes like required
or pattern
to enforce specific data formats or ensure that a field is not empty.
When an input element meets its validation criteria, it is considered "valid," and the :valid
pseudo-class can be used to apply styling to it. This can be helpful to provide visual feedback to users, indicating that their input is correct.
Here's a simple example of how the :valid
pseudo-class can be used in CSS:
input:valid {
border: 2px solid green; /* Add a green border to valid input */
}
In this example, when an input field contains valid data according to its constraints, it will have a green border applied to it. This visual cue can be helpful for users to understand that their input meets the required criteria. Conversely, when input is invalid, you can use the
:invalid
pseudo-class to apply different styling for indicating errors or prompting users to correct their input.
Syntax
:valid { /* ... */ }
Example
<p>URL</p>
<p><input type="url" required></p>
<p>Email</p>
<p><input type="email" required></p>
<p><input type="submit" value="Submit"></p>
input[type=url]:invalid, input[type=email]:invalid {
background: #fdd;
padding: 3px 10px;
}
input[type=url]:valid, input[type=email]:valid {
background: #dfd;
padding: 3px 10px;
}
Browser Support
The following table will show you the current browser support for the CSS :valid
pseudo class.
Desktop | |||||
12 | 10 | 4 | 10 | 5 |
Tablets / Mobile | |||||
18 | 4 | 10.1 | 5 | 1 | 37 |
Last updated by CSSPortal on: 1st October 2023