Platinum Partner
css,html5,html & xhtml,webdev

Using The :invalid CSS Pseduo Class

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 {{ articles[0].authors[0].realName }}, DZone MVB. (source)

Opinions expressed by DZone contributors are their own.

{{ tag }}, {{tag}},

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

{{ parent.tldr }}

{{ parent.urlSource.name }}
{{ parent.authors[0].realName || parent.author}}

{{ parent.authors[0].tagline || parent.tagline }}

{{ parent.views }} ViewsClicks
Tweet

{{parent.nComments}}