CSS :optional
selector is used to select and style optional form elements. A form element is treated as an optional element if it does not have the required
attribute.
The :optional selector only applies to the <input>, <select> and the <textarea> form elements.
The :optional
selector in the following example selects all <input> elements that do not have the required
attribute and sets a yellow background to them:
Example:
input:optional{ background-color: yellow; }
Here is another example with the <textarea>
form fields:
Example:
textarea:optional{ background-color: yellow; }
The :optional selector can also be used with other pseudo-class as well as pseudo-element selectors. It means that you can select all optional elements on a page and add styles to them on hover, focus, active, valid, invalid, etc.
The :optional
selector in the following example sets a yellow background to the optional input elements as soon as you hover over them:
Example:
input:optional:hover{ background-color: yellow; }
CSS Syntax
The syntax of the :optional
selector is as follows:
:optional{ CSS Styles; }
Browser Support
The number in each cell of the table specifies the first version of the browser that fully supports the :optional
selector.
Selector | |||||
:optional | 10.0 | 10.0 | 4.0 | 5.0 | 10.0 |