CSS :out-of-range
The CSS :out-of-range pseudo-class targets input elements whose values fall outside the defined min
and max
range. This is useful for styling form elements to visually indicate invalid data that does not meet the specified range criteria.
The syntax for the :out-of-range
pseudo-class is:
</>
Copy
selector:out-of-range {
property: value;
}
Where:
Parameter | Description |
---|---|
selector | The form element (e.g., <input> ) to which the :out-of-range pseudo-class will apply. |
property | The CSS property to style the element. |
value | The value assigned to the CSS property. |
Examples
1. Styling Number Inputs Outside Range
In this example, number input fields with values outside the range of 1 to 10 are styled with a red border.
index.html
</>
Copy
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
input:out-of-range {
border: 2px solid red;
}
input:in-range {
border: 2px solid green;
}
</style>
</head>
<body>
<form>
<label>Enter a number (1-10):</label>
<input type="number" min="1" max="10" required>
</form>
</body>
</html>
2. Styling Date Inputs Outside Range
In this example, date input fields outside a specific date range are styled with a red outline.
index.html
</>
Copy
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
input[type="date"]:out-of-range {
outline: 2px solid red;
}
input[type="date"]:in-range {
outline: 2px solid green;
}
</style>
</head>
<body>
<label>Select a date (2023-01-01 to 2023-12-31):</label>
<input type="date" min="2023-01-01" max="2023-12-31" required>
</body>
</html>
3. Styling Time Inputs Outside Range
Here, time inputs outside the range of 9:00 AM to 5:00 PM are styled with a yellow background.
index.html
</>
Copy
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
input[type="time"]:out-of-range {
background-color: yellow;
}
input[type="time"]:in-range {
background-color: lightgreen;
}
</style>
</head>
<body>
<label>Select a time (9:00 AM - 5:00 PM):</label>
<input type="time" min="09:00" max="17:00" required>
</body>
</html>