Skip to content
Tutorials Center
My learning

Topics

CSS Reference ยท Pseudo-classes

The :invalid pseudo-class

Reference for the CSS :invalid pseudo-class: style controls whose value fails HTML validation, why empty required fields match on load, and better options.

The :invalid pseudo-class matches form controls, fieldsets and forms whose value fails HTML constraint validation: a missing required value, a wrong type such as a malformed email, a pattern mismatch, or a number outside min and max.

The pseudo-class is evaluated continuously, including on page load. That is its main trap: an empty required field is invalid before the user has done anything.

CSS
input:invalid {
  border-color: #dc2626;
}

Try it

Invalid fields, but only after typing

Syntax

CSS
:invalid { /* declarations */ }
  • Applies to: <input>, <select>, <textarea>, <fieldset>, <form> and form-associated custom elements.
  • Specificity: (0,1,0).
  • Inherited / animatable: not applicable.

Values

Syntax and arguments Description
:invalid No arguments. Matches an element that fails at least one constraint. A form or fieldset matches when any control inside it is invalid.

Usage notes

  • Red on load. Required empty fields match immediately. Delay feedback with :not(:placeholder-shown) (needs a placeholder), or use :user-invalid, which waits for user interaction.
  • Firefox history. Old Firefox versions added a red glow to invalid fields by default; modern browsers do not.
  • Forms match too. form:invalid can disable a submit button visually, but also keep the button usable so users can discover what is wrong.
  • Not for every control. Disabled, read-only and hidden inputs and buttons are not validated, so they match neither :valid nor :invalid.
  • Show text, not only colour. Add a message (aria-describedby) and aria-invalid where useful. Colour alone fails users with colour blindness.
  • novalidate. The attribute stops the browser blocking submission, but :invalid still matches.

Browser support

Supported in every browser.