How to Style Mandatory Fields with CSS3 Pseudo-Selectors

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:

Join us in our newest publication:
  1. <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:

  1. :required{
  2. border: 1px solid red;
  3. }

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.

Share and Enjoy !

0Shares
0 0