:optional CSS Pseudo Class

If this site has been useful, we’d love your support! Running this site takes time and resources, and every small contribution helps us keep creating valuable content. Consider buying us a coffee to keep things going strong!

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
Edge Chrome Firefox Opera Safari
12104105
Tablets / Mobile
Chrome Firefox Opera Safari Samsung Webview
18410.15137

Last updated by CSSPortal on: 1st October 2023