:required

Term side of the Card.
Topic: Pseudo Classes
Unit title: :required
Categories: Pseudo-class
Explanation side of the Card

Explanation: The pseudo-class that selects form elements with the `required` attribute. It applies to fields that must be filled out before a form can be submitted, enabling specific styling to indicate the importance of these fields to the user.

Browser compatibility:
  • The chrome browser supports this feature starting from version 10.
  • The edge browser supports this feature starting from version 12.
  • The firefox browser supports this feature starting from version 4.
  • The safari browser supports this feature starting from version 5.
Availability: 

Example

Wrongcss
input:required::after {
  content: ' *';
  color: red;
}
Rightcss
label:has(+ input:required)::after {
  content: ' *';
  color: #c00;
}

Inputs can't have ::after content, so the asterisk goes on the label next to the required field.

Common mistakes

  • Adding an asterisk with ::after on the input, where it never shows.
  • Marking fields required only visually, so the browser and screen readers don't know.

Key points

  • Required fields have the required attribute, not only a CSS asterisk or class.
  • The required state is also visible in the label text, not just from color or ::after content.
  • Code does not expect :required to match custom controls without the required attribute.

Interview questions

Which elements can match :required?

input, select and textarea with the required attribute.

Do I still need aria-required if I use required?

No. The native required attribute is already announced, so aria-required is only for custom controls.

Analytics cookiesWe'd like to use analytics cookies to see which pages are useful. They're set only if you accept. Privacy Policy