:optional CSS Pseudo Class
Description
The :optional
pseudo-class in CSS is used to select and style form elements that are not required or mandatory for user input. It is particularly useful for styling optional form fields differently from required ones, providing visual cues to users that certain input fields are not obligatory.
For instance, if you have a form with some optional fields like an optional phone number or additional comments, you can use the :optional
pseudo-class to apply unique styling, such as different colors or borders, to these fields. This helps users easily identify which fields they can skip without affecting the submission of the form.
Here's a simple example of how you might use the :optional
pseudo-class in CSS:
input:optional {
border: 1px solid #ccc;
color: #666;
}
In this example, all optional input fields will have a light gray border and a slightly muted text color, making them visually distinct from required fields.
Syntax
:optional { /* ... */ }
Example
<p>Please enter your name and age.</p>
<p>Name: <input name="name" required ></p>
<p>Age: <input type="number" name="old"> (Optional)</p>
<p><button>Submit</button></p>
input:optional {
border:1px dashed green;
}
Browser Support
The following table will show you the current browser support for the CSS :optional
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