:invalid CSS Pseudo Class
Description
The :invalid pseudo-class in CSS is used to select form elements that fail to meet the constraints set by HTML attributes such as input type, pattern, minlength, maxlength, or other validation-related attributes. This pseudo-class allows developers to apply specific styles to form fields that contain invalid data, providing immediate visual feedback to users before the form is submitted. It is particularly useful in improving user experience by highlighting errors in real time.
The :invalid pseudo-class works in conjunction with the :valid pseudo-class, enabling developers to define complementary styles for valid and invalid inputs. It is commonly used with border-color, background-color, color, and box-shadow properties to make invalid fields stand out. For example, setting a red border on an input field when it fails validation can alert the user immediately that their input requires correction.
The behavior of :invalid depends on the browser’s native form validation rules and the specific input type. For example, an input with type="email" will automatically trigger :invalid if the value entered does not match the correct email format. Additionally, :invalid can be combined with other pseudo-classes such as :focus to style an element differently when it is both focused and invalid.
Example:
<form>
<label for="email">Email:</label>
<input type="email" id="email" required>
<button type="submit">Submit</button>
</form>
input:invalid {
border: 2px solid red;
background-color: #ffe6e6;
}
input:valid {
border: 2px solid green;
background-color: #e6ffe6;
}
In this example, the input field will have a red border and light red background whenever the entered value is not a valid email address. Once the user enters a correctly formatted email, the field changes to green, indicating validity. Using :invalid improves form usability and reduces the likelihood of submitting incorrect data.
Syntax
:invalid {
/* ... */
}
Example
Browser Support
The following information will show you the current browser support for the CSS :invalid pseudo class. Hover over a browser icon to see the version that first introduced support for this CSS psuedo class.
This psuedo class is supported by all modern browsers.
Desktop
Tablets & Mobile
Last updated by CSSPortal on: 31st December 2025
