CSS Tip - Overriding CSS 3 Pseudo-Classes

While using CSS 3 pseudo-classes I ran into situations where I needed to programatically disable/change styles that were auto applied by the browsers. Todays article explains how to override styles applied by pseudo-class.

Getting ready

Two new and useful pseudo-classes introduced in the HTML 5 compliant browsers are :invalid and :valid. The styles set to these pseudo-classes are applied when various HTML 5 input attributes are processed. Assume the following CSS, which applies a red border when invalid and a green border when valid:

input:invalid {
	border-color: red;
}
input:valid {
	border-color: green;
}

Now assume the following form element for an american zipcode (a value is required and 3-5 numbers are expected):

<input required pattern="\d{3,5}" name="zipcode" value=""/>

The problem with zipcodes is there are a lot of numbers between 100 and 99999 that pass the regular expression validation, but are not actual zipcodes. Most developers use JavaScript to send a request to the server, where they evaluate the zipcode entered, and return the status. But if the value is asynchronously determined to be invalid and the browser validated it as valid (applying the :valid pseudo-class styles), what is the best way to show the values proper invalidity.

For example, if the user enters 449, the browser will mark the form as :valid, but it is actually an invalid zipcode and the browser applied pseudo-class needs to be overwritten.

How to do it&hellip

The solution is to apply a class to a parent element and then use that class to override the default behavior. The CSS above has been augmented with the two new classes:

.force_invalid input:valid,
input:invalid {
	border-color: red;
}
.force_valid input:invalid,
input:valid {
border-color: green;
}

So, by applying the class force_invalid to a parent element of the zipcode input when the AJAX request informs of an invalid zipcode and the input will no longer appear valid. For example, you might have markup like the following:

<li class="force_invalid">
	<input required pattern="\d{3,5}" name="zipcode" value=""/>
</li>

How it works&hellip

The force_invalid class applies a higher specificity to the pseudo-classes, which overrides the original styling with the opposite. Although, relatively straight forward, this technique is simple, re-uses the existing styles, and is often overlooked. Additionally, the technique can be applied to any pseudo-class, not just the new HTML 5 and CSS 3 ones.