Briefly
The :required
pseudo-class, complementing the main selector, will help select elements <input>
, <textarea>
or <select>
that have the required
attribute set.
Example
A required input field will have an orange border and background color:
<form> <div class="form-row"> <label for="first_name">Name</label> <input type="text" id="first_name" required> </div> <div class="form-row"> <label for="last_name">Last Name</label> <input type="text" id="last_name"> </div></form>
<form> <div class="form-row"> <label for="first_name">Name</label> <input type="text" id="first_name" required> </div> <div class="form-row"> <label for="last_name">Last Name</label> <input type="text" id="last_name"> </div> </form>
input:required { border-width: 2px; border-color: #FF8630; background-color: rgb(255 134 48 / 0.1);}
input:required { border-width: 2px; border-color: #FF8630; background-color: rgb(255 134 48 / 0.1); }
How to Understand
If you need to somehow highlight the required elements of forms, you can use the :required
pseudo-class in the selector.
In practice
Advice 1
🛠 As a rule, in real forms, the required fields are not highlighted as clearly as in the example above. Usually, an asterisk is placed after the text description of the required field. In the example below, it is also shown how to style the hint for the field.
<form> <div class="form-row"> <label class="label-required" for="first_name">Name</label> <input type="text" id="first_name" required> <span class="hint">Required</span> </div> <div class="form-row"> <label for="last_name">Last Name</label> <input type="text" id="last_name"> <span class="hint">Optional</span> </div></form>
<form> <div class="form-row"> <label class="label-required" for="first_name">Name</label> <input type="text" id="first_name" required> <span class="hint">Required</span> </div> <div class="form-row"> <label for="last_name">Last Name</label> <input type="text" id="last_name"> <span class="hint">Optional</span> </div> </form>
.label-required::after { content: "*"; font-size: 0.7em;}.hint { color: #FFFFFF;}input:required + .hint { color: #2E9AFF;}
.label-required::after { content: "*"; font-size: 0.7em; } .hint { color: #FFFFFF; } input:required + .hint { color: #2E9AFF; }