Codectionary / Developer documentation / CSS

Form State Pseudo-classes

CSS can style form elements based on their validation and interaction state without any JavaScript. :checked applies to checked checkboxes/radios, :disabled to disabled fields, :required and :optional based on the required attribute, and :valid/:invalid based on constraint validation results.

Syntax

:checked, :disabled, :required, :valid, :invalid

Examples

Styling Checked and Disabled States

Visual feedback for checkbox state and disabled fields.

input[type="checkbox"]:checked {
  accent-color: #3b82f6; /* tints the native checkbox */
}

input:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

Live Validation Styling

Giving instant visual feedback based on native HTML validation.

input:required {
  border-left: 3px solid #f59e0b; /* marks required fields */
}

input:invalid:not(:placeholder-shown) {
  border-color: red; /* only show invalid state once the user has typed something */
}

input:valid:not(:placeholder-shown) {
  border-color: green;
}

Parameters and values

  • :checked (pseudo-class): Matches checked checkboxes, radios, or selected options
  • :disabled / :enabled (pseudo-class): Matches based on the disabled attribute
  • :required / :optional (pseudo-class): Matches based on the required attribute
  • :valid / :invalid (pseudo-class): Matches based on constraint validation results

Best practices

  • Combine :invalid with :not(:placeholder-shown) to avoid showing an error state before the user has even had a chance to type
  • Use :checked alongside the sibling combinator (~) as a classic CSS-only technique for building toggles and accordions without JavaScript
  • Style :disabled fields clearly (reduced opacity, not-allowed cursor) so users understand why they cannot interact with them
  • Remember :valid/:invalid reflect the browser's native HTML validation - custom JavaScript validation needs its own styling approach, like conditional classes

At a glance

Purpose
Presentation and layout
File extension
.css
Runs in
Web browsers
Usually used with
HTML and JavaScript

Specifications & further reading

Related CSS documentation