CSS :optional
Pseudo-Class
The :optional
pseudo-class selects <input>
elements that are not required (i.e., they don't have the required
attribute). This is useful for styling optional form fields differently from required ones.
1. Syntax
✅ Targets all <input>
fields without the required
attribute.
2. Example – Styling Optional vs. Required Fields
✅ Optional fields have a blue border.
❌ Required fields have a red border.
3. Example – Highlighting Optional Fields on Focus
✅ When an optional field is focused, it gets a green outline.
4. :optional
vs. :required
Pseudo-Class | Applies To |
---|---|
:optional | Inputs without required . |
:required | Inputs with required . |
5. Browser Support
✅ Fully supported in Chrome, Edge, Firefox, Safari, and Opera.
6. Best Practices
✔ Use :optional
to differentiate required and optional fields.
✔ Combine it with :required
for a better form UI.
✔ Works great with :focus
and :valid
for an enhanced user experience.