CSS Reference Pseudo-class

:optional

:optional is a CSS pseudo-class selector used to select form elements that are optional.

More specifically, it is used to select form elements that are not required; that is, form elements that do not have the required attribute set.

The form elements than can be selected using :optional are <input>s, <select>s, and <textarea>s without a required attribute.

For example, the following form elements can be selected using :optional:

<input type="text">

<input type="submit">

<!-- and other input types as well.. -->

<textarea name="name" id="id" cols="30" rows="10"></textarea>

<select name="nm" id="sel">
    <!-- options -->
</select>
                

The following form elements can not be selected using :optional:

<input type="name" required>

<input type="email" required>

<!-- and other input types as well.. -->

<textarea name="name" id="message" cols="30" rows="10" required></textarea>

<select name="nm" id="sel" required>
    <!-- options -->
</select>
                

:optional is useful for styling optional form elements in a way that would put less visual focus on them and more focus on the required fields.

Trivia & Notes

If you want to select form elements that are required, you can use the :required pseudo-class selector.

Just like other pseudo-class selectors, the :optional selector can be chained with other selectors such as :hover and with pseudo-elements such as ::after, among others. For example, the following rule will provide hover styles for an optional text area:

textarea:optional:hover {
    /* content and styles here */
}
                

Examples

The following will give slightly faded styling to an input which asks the user for a website URL. This is usually an optional field in comment forms, for example.

input[type="url"]:optional {
    background-color: #f5f5f5;
    border: 1px solid #eee;
}
                

Live Demo

In the following demo, both the :optionaland the :required pseudo-class selectors are used to style form elements that are optional and required, respectively, to make required forms stand out visually.

View this demo on the Codrops Playground

Browser Support

The :optional pseudo-class selector is supported in Chrome 10+, Firefox, Safari, Opera 10+, Internet Explorer 10+, and on Android and iOS.

Written by . Last updated February 3, 2015 at 12:33 pm by Manoela Ilic.

Do you have a suggestion, question or want to contribute? Submit an issue.