Categories
Web development

CSS :valid & :invalid Selectors

CSS :valid and :invalid selectors

CSS :valid selector

The CSS :valid selector defines form element with a value that validates according to the element’s settings.

Syntax:

:valid {
  CSS declarations;
} 

CSS :invalid selector

The CSS :invalid selector defines form elements with a value that does not validate according to the element’s settings.

Syntax:

 :invalid {
  CSS declarations;
} 

Example:

<!DOCTYPE html>
<html>
<head>
<style>
input:valid {
  background-color: #e9c46a;
}
    
input:invalid {
  border: 2px solid #e76f51;
}
</style>
</head>
<body>

<h4>:valid selector:</h4>

<input type="email" value="example@example.com">
    
<p>Try to type a not valid e-mail address, to see the styling disappear.</p>
</br>
    
<h4>:invalid selector:</h4>
<input type="email" value="exampleEmail">

<p>Try to type a valid e-mail address, to see the styling disappear.</p>


</body>
</html>

Output:

:valid selector:

Try to type a not valid e-mail address, to see the styling disappear.


:invalid selector:

Try to type a valid e-mail address, to see the styling disappear.

>

Note: The CSS :valid and :invalid selectors only work for form elements such as input elements.

Enjoy coding!