Categories
Web development

CSS :optional & :required Selectors

CSS :optional and :required selectors

CSS :optional selector

The CSS :optional selector matches form elements that are optional.

Syntax:

:optional {
  CSS declarations;
} 

CSS :required selector

The CSS :required selector matches form elements that are required.

Syntax:

:required {
  CSS declarations;
}

Example:

<!DOCTYPE html>
<html>
<head>
<style>
input:optional {
  background-color: #e9c46a;
}
    
input:required {
  background-color: #f4a261;
}
</style>
</head>
<body>

<p>An optional input element:<br><input></p>

<p>A required input element:<br><input required></p>


</body>
</html>

Output:

An optional input element:

A required input element:

Note: The CSS :optional and :required selectors only applies to the form elements like <input>, <select>, and <textarea>.

Enjoy coding!

Read also:

CSS :hover and :active selectors

CSS :focus & :focus-within Selectors