Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Using The :invalid CSS Pseduo Class

DZone's Guide to

Using The :invalid CSS Pseduo Class

· Web Dev Zone
Free Resource

Start coding today to experience the powerful engine that drives data application’s development, brought to you in partnership with Qlik.

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.

Create data driven applications in Qlik’s free and easy to use coding environment, brought to you in partnership with Qlik.

Topics:

Published at DZone with permission of Paul Underwood, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

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

{{ parent.tldr }}

{{ parent.urlSource.name }}