The :required
pseudo-class selects form elements that have the required
attribute. It allows you to visually distinguish fields that must be filled out from optional ones.
Example 1: Asterisk for Required Fields
/* This CSS adds a red asterisk after the label of a required input. */
label.required::after {
content: ' *';
color: red;
}
Explanation
A common convention is to mark required fields with an asterisk. This CSS automatically adds a red asterisk to the content of any label with the class required
.
Example 2: Highlighting Required Empty Fields
/* This CSS rule targets required inputs that are empty. */
input:required:placeholder-shown {
/* A yellow border indicates a required but unfilled field. */
border: 1px solid gold;
}
Explanation
This code uses the :placeholder-shown
pseudo-class in conjunction with :required
to highlight required fields that have not yet been filled out by the user.
Example 3: Required Field Background Color
/* This CSS rule sets a light blue background for all required fields. */
input:required, textarea:required {
background-color: #eaf6ff;
}
Explanation
This CSS helps users quickly identify all the mandatory fields on a form by giving them a distinct background color.
Example 4: Bold Labels for Required Fields
/* This CSS makes the label text of a required input bold. */
input:required + label {
font-weight: bold;
}
Explanation
This example makes the labels of required fields bold, providing a clear visual distinction from the labels of optional fields. The adjacent sibling selector targets the label immediately following the required input.
Example 5: Custom Outline on Focused Required Fields
/* This CSS provides a custom outline when a required field is focused. */
input:required:focus {
/* A blue outline is applied on focus. */
outline: 2px solid #007bff;
outline-offset: 2px;
}
Explanation
This CSS enhances the focus state for required fields. When a user tabs into or clicks on a required input, a prominent blue outline appears, guiding their focus.