Introduction to the :out-of-range Selector in CSS

css out of range selector
10 November 2024

CSS selectors are powerful tools that give us the ability to precisely target HTML elements and apply styles to them. The :out-of-range selector is one of those selectors that is commonly used in various HTML forms. This selector allows us to indicate to the user when the input values exceed the specified limits.
If we assume in a form, the user must enter a number between 1 and 10. If the user enters a number outside of this range, we can use :out-of-range to visually indicate these inputs and, for example, change their color, so the user realizes their mistake.

This is a simple yet very effective way to enhance user experience and provide greater control over user inputs. The :out-of-range selector specifically applies to inputs with the type attributes like number and range.

By using this selector, we can create specific styles for cases where user input exceeds the minimum and maximum limits specified, creating a more engaging experience overall. We can also use it to create visually appealing effects based on user interactions.

The following code example demonstrates how to use the :out-of-range selector.


<form>
<label for="age">Enter your age: </label>
<input type="number" id="age" name="age" min="1" max="10">
</form>

<style>
input:out-of-range {
border-color: red;
background-color: #ffdada;
}
</style>

Line by Line Code Explanation

<form> | This HTML tag creates a form that holds the inputs and their associated labels.
<label for="age"> | With this tag, we create a label for the input which is specifically tied to the input with the id age.
<input type="number"> | This input allows the user to enter a number, particularly of type number.
min="1" max="10" | These are attributes that define the minimum and maximum permissible values for the input.
input:out-of-range | This CSS selector applies to inputs where the values exceed the specified minimum and maximum limits.
border-color: red; | When the input is outside the specified limits, the border turns red.
background-color: #ffdada; | The background of the input changes to this color when it is outside the limits, making it more noticeable.

FAQ

?

How can I determine which inputs use :out-of-range?

?

Is :out-of-range limited to specific input types?

?

Can the :out-of-range selector work alongside other selectors?