CSS :invalid
selector allows you to style an <input>
element only if the value that it contains is invalid. The value that it contains is invalid or not is decided by the element’s settings.
For example, if we take an <input>
element with type="number"
and set its limits using the min="10"
and max="20"
attributes, it expects a value between 10 and 20.
If the value entered in this input element is between 10 and 20, it’s a valid value. Otherwise, it will be considered an invalid value. It means that the :invalid
selector will only work for the values that aren’t between 10 & 20.
The :invalid
selector in the following example sets a pink color background to the <input>
element only if the value that it contains is not between 10 and 20:
Example:
input:invalid{ background-color: pink; }
The :invalid
selector in the following example sets a pink color background to the <input> element only if it contains an invalid email address.
Example:
input[type="email"]:invalid{ background-color: pink; }
CSS Syntax
The syntax of the :invalid
selector is as follows:
:invalid{ CSS Styles; }
Browser Support
The number in each cell of the table specifies the first version of the browser that fully supports the :invalid
selector.
Selector | |||||
:invalid | 10.0 | 10.0 | 4.0 | 5.0 | 10.0 |