Over a million developers have joined DZone.
Platinum Partner

Using The :invalid CSS Pseduo Class

· Web Dev Zone

The Web Dev Zone is brought to you in partnership with Mendix.  Discover how IT departments looking for ways to keep up with demand for business apps has caused a new breed of developers to surface - the Rapid Application Developer.

HTML comes with a set of standards which front-end developers must compile to in order for your HTML elements to be rendered correctly.

Luckily HTML is a very forgiving language and the browsers will do its best to display the HTML correctly even if the element is defined incorrectly. But HTML will have to guess what you intended to do so the output might look different.

The things which are commonly missed in front-end development can be missing quotes, missing closed tags or incorrect tags which the browser doesn't understand. The best way to check if your HTML is correctly is to run it through a validator.

W3C HTML Validator

The most popular HTML validator people use is the W3C Markup validator.

W3C Validator

The W3C Markup Validation Service

You can choose to validate your website by typing in the URL of the page, providing a file to upload or directly copying in the HTML to be validated.

Validate HTML With CSS

There is a new CSS pseudo-class, which can be used to style an input or a form tag differently if it has failed validation. This means that you can make invalid HTML elements stand out when you display the page making it easy to see which element does not validate.

The pseudo-class you need to use is :invalid.

:invalid {
    background-color: #ffdddd;

Browser Support

This class is currently supported on the following browsers.

  • Chrome 10 or higher
  • Firefox 4.0 or higher
  • IE 10
  • Opera 10
  • Safari 5.0

Example Using The Invalid Class

In this example we show how the invalid class works on a basic form.

<style type="text/css">
  :invalid {
    background-color: #ffdddd;
  :valid {
    background-color: #ddffdd;
<label>Username</label><input type="text" />
<label>Email</label><input type="email" required />



As you can see from this example the Email text box is highlighted red because of the required attribute is not valid HTML.

The Web Dev Zone is brought to you in partnership with Mendix.  Learn more about The Essentials of Digital Innovation and how it needs to be at the heart of every organization.


Published at DZone with permission of Paul Underwood , DZone MVB .

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}