CSS Pseudo Classes for Form Elements

Apr282014

CSS provides us with a handful of pseudo classes that are specific to HTML5 forms. They allow us to create forms that are easier to fill out by highlighting fields that are required, optional, valid, invalid, etc.

Pseudo Classes for Forms

The following pseudo classes are all related to form elements with examples on how they are used.

:default

The :default pseudo class applies to the default element in a group of similar elements within a given form. For example, if you have a form that has a submit and cancel button you could select the default button using :default.

:optional

The :optional pseudo class applies to any input without the required attribute set within a given form. May or may not be useful since most of the time simply highlighting the required fields will be enough.

:in-range

The :in-range pseudo class applies to any form element that contains a value within the specified range for the input within a given form. Similar to valid/invalid it can be useful for providing feedback to the user when filling out the form.

:out-of-range

The :out-of-range pseudo class applies to any form element that contains a value outside the specified range for the input within a given form. Similar to valid/invalid it can be useful for providing feedback to the user when filling out the form.

:read-write

Client Side Only

The important thing to remember when using CSS and HTML validation to style your forms is that they are only client side validation. You will still need to validate on the server as well. The role that CSS and these pseudo classes play is to simply enhance the form and make it easier for users to fill out.