:optional

Term side of the Card.
Topic: Pseudo Classes
Unit title: :optional
Categories: Pseudo-class
Explanation side of the Card

Explanation: The pseudo-class that selects form elements that are not required and can be left empty. It helps style optional form fields differently from required ones, making it easier to indicate which fields are necessary for submission.

Browser compatibility:
  • The chrome browser supports this feature starting from version 10.
  • The edge browser supports this feature starting from version 12.
  • The firefox browser supports this feature starting from version 4.
  • The safari browser supports this feature starting from version 5.
Availability: 

Example

Wrongcss
input:optional {
  opacity: 0.5;
}
Rightcss
label:has(+ input:optional)::after {
  content: ' (optional)';
  color: #555;
}

A text hint marks the field as optional without making it look disabled or hard to read.

Common mistakes

  • Expecting :optional to match buttons or custom controls built from div elements.
  • Styling optional fields faintly so they look disabled.

Key points

  • :optional targets input, select and textarea elements without the required attribute.
  • An optional field is labeled as optional in text, not only by a style difference.

Interview questions

Is :optional the opposite of :required?

Yes, for form fields. A field that can be required matches exactly one of :required and :optional.

Should I mark required or optional fields?

Mark whichever is rarer in the form, and say it in text so every user notices.

Analytics cookiesWe'd like to use analytics cookies to see which pages are useful. They're set only if you accept. Privacy Policy