CSS :optional Pseudo Class

CSS :optional Pseudo Class

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

input:optional { /* Styles for optional fields */ }

✅ Targets all <input> fields without the required attribute.

2. Example – Styling Optional vs. Required Fields

<form> <label for="name">Name (required):</label> <input type="text" id="name" required> <label for="nickname">Nickname (optional):</label> <input type="text" id="nickname"> <button type="submit">Submit</button> </form>
input:optional { border: 2px solid blue; background-color: #e7f1ff; } input:required { border: 2px solid red; background-color: #ffe7e7; }

Optional fields have a blue border.
Required fields have a red border.

3. Example – Highlighting Optional Fields on Focus

input:optional:focus { outline: 3px solid green; }

✅ When an optional field is focused, it gets a green outline.

4. :optional vs. :required

Pseudo-ClassApplies To
:optionalInputs without required.
:requiredInputs 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.

Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close