1 min read

CSS :in-range and :out-of-range Pseudo-classes

The :in-range and :out-of-range pseudo-classes allow you to style inputs that have range limitations (using min and max attributes) based on whether their current value is within those limits.

1. :in-range

The :in-range pseudo-class represents an input element whose current value is within the bounds specified by the min and max attributes.

/* Style inputs that are within the valid range */
input:in-range {
  background-color: rgba(0, 255, 0, 0.1);
  border-color: green;
}

2. :out-of-range

The :out-of-range pseudo-class represents an input element whose current value is outside the bounds specified by the min and max attributes.

/* Style inputs that are outside the valid range */
input:out-of-range {
  background-color: rgba(255, 0, 0, 0.1);
  border-color: red;
}

3. Example

This is commonly used with type="number" or type="range".

<label for="age">Age (18-100):</label>
<input type="number" id="age" min="18" max="100" value="25">
  • If the user types 25: Matches :in-range.
  • If the user types 10: Matches :out-of-range.
  • If the user types 150: Matches :out-of-range.

4. Relationship with :valid / :invalid

  • :in-range implies :valid (regarding range constraints).
  • :out-of-range implies :invalid.

However, :valid and :invalid cover all constraints (like required, pattern, type), whereas :in-range / :out-of-range specifically target numeric ranges.

programming/css/css programming/css/pseudo-classes-and-pseudo-elements programming/css/valid-and-invalid-pseudo-classes