How to Style Mandatory Fields with CSS3 Pseudo-Selectors

Published August 15, 2016 by CSS Newbies.

It’s not uncommon for mandatory fields in a form to be marked as such — often these fields are marked with an asterisk or with a colored border around the input so that the user is aware that the particular form can’t be submitted without the required fields being filled out. With CSS3’s pseudo-selector :required, it’s easy to single out these required fields and apply styling to them.

To start, you’re going to need an input field. Make to mark your input’s HTML with ‘required’ so the CSS code will know where to apply the styling. Here’s an example:

<input <strong>required</strong> type="text" name="email">

See how the word ‘required’ immediately follows the input tag? To add a border to this input, your CSS should look like this:

border: 1px solid red;

Here’s what your final results should look like:

Screen Shot 2016-08-14 at 3.42.04 PM

Similarly, you can also use the :optional pseudo-selector to style any optional input fields. To use this pseudo-selector,  you don’t need to mark any of the input fields as optional like you do with the required fields — any styling defined with the :optional pseudo-selector will automatically be applied to any input fields that aren’t marked as required.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>