Sel Invalid
## CSS :invalid Pseudo-class Selector
The `:invalid` CSS pseudo-class represents any `` or other `
```
```css
/* Apply a red border and light red background to invalid inputs */
input:invalid {
border: 2px solid #ff4d4d;
background-color: #ffe6e6;
}
/* Optional: Apply a green border to valid inputs for contrast */
input:valid {
border: 2px solid #2ecc71;
background-color: #eafaf1;
}
```
### Example 2: Displaying Validation Error Messages
You can combine `:invalid` with sibling combinators (like `+` or `~`) to show or hide helper text dynamically.
```html
```
```css
/* Hide the error message by default */
.error-message {
display: none;
color: #ff4d4d;
font-size: 0.85em;
margin-top: 5px;
}
/* Show the error message only when the input is invalid and focused */
input:invalid:focus + .error-message {
display: block;
}
```
---
## Browser Support
The `:invalid` pseudo-class has excellent modern browser support:
| Selector | Chrome | Edge / IE | Firefox | Safari | Opera |
| :--- | :--- | :--- | :--- | :--- | :--- |
| **`:invalid`** | 10.0+ | 10.0+ | 4.0+ | 5.0+ | 10.0+ |
---
## Important Considerations
1. **Immediate Validation (The "Pre-flight" Issue):** By default, browsers apply `:invalid` styles as soon as the page loads. If you have a `required` field, it will appear invalid (e.g., red) before the user even has a chance to type.
* *Solution:* To prevent this, you can use the modern `:user-invalid` pseudo-class. `:user-invalid` only represents an element that is invalid *after* the user has interacted with it.
2. **Form-Level Validation:** You can also target entire `
YouTip