It appears that the pseudo-classes :in-range
and :out-of-range
behave similarly to the :valid
and :invalid
selectors. This results in the input
element always being in one of these states, preventing the default selector from being applied. Interestingly, even a blank value is considered to be in range, despite seeming otherwise. The selectors specification does not address this specific scenario.
An advisable solution would be to set a default value for the field (e.g., value="0"
) since it is mandatory. However, if you find that the default red background negatively impacts the user experience, consider the following alternative approach.
By adding the required
attribute to the input
(given its mandatory nature) and combining it with the :valid
and :invalid
selectors, the desired outcome can be achieved.
input:invalid
- Applied in cases of default or blank values as they are deemed invalid due to the field's required status.
input:in-range:valid
- Selects any valid value within the specified range.
input:out-of-range:invalid
- Identifies values outside the defined range as invalid, triggering the red color only when relevant.
Note for future readers: While the suggested workaround may suffice for some scenarios, it is worth noting that users may expect a blank value in a required field to also trigger an invalid state with a red background. It is advised to evaluate and apply cautiously.
input:invalid {
background: white;
color: white;
}
input:in-range:valid {
background: green;
color: white;
}
input:out-of-range:invalid {
background: red;
color: white;
}
<h3> CSS range validation </h3>
Enter your age
<input type="number" min="1" max="100" required>