# CSS `:required` and `:optional` Pseudo-classes

The `:required` and `:optional` pseudo-classes allow you to style form elements based on whether they have the `required` attribute set. This provides visual feedback to users about which fields are mandatory.

## 1. `:required`

The `:required` pseudo-class represents any `<input>`, `<select>`, or `<textarea>` element that has the `required` attribute set.

```html
<input type="text" required>
```

```css
/* Style required inputs */
input:required {
  border-left: 4px solid red;
}

/* Add an asterisk after the label of a required input */
label:has(+ input:required)::after {
  content: " *";
  color: red;
}
```

## 2. `:optional`

The `:optional` pseudo-class represents any form element that does *not* have the `required` attribute set.

```html
<input type="text"> <!-- Optional by default -->
```

```css
/* Style optional inputs */
input:optional {
  background-color: #f9f9f9;
  border-left: 4px solid green;
}
```

## 3. Use Cases

*   **Visual Cues:** Instantly show users which fields they can skip.
*   **Validation Feedback:** Combine with `:valid` or `:invalid` to create robust form validation styles.

```css
input:required:invalid {
  border-color: red;
}
```

[[programming/css/css]]
[[programming/css/pseudo-classes-and-pseudo-elements]]
[[programming/css/selectors]]
[[programming/css/has-pseudo-class]]