HTML5 Zone is brought to you in partnership with:

Paulund is a website dedicated to writing tutorials and code snippets about Web Development, the main subjects are PHP, Wordpress, jQuery, CSS3 and HTML5. Paul is a DZone MVB and is not an employee of DZone and has posted 137 posts at DZone. You can read more from them at their website. View Full User Profile

Using The :invalid CSS Pseduo Class

09.12.2012
| 4105 views |
  • submit to reddit

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;
  }
</style>
<form>
<label>Username</label><input type="text" />
<label>Email</label><input type="email" required />
</form>

Username

Email

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

Published at DZone with permission of Paul Underwood, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)