How to Style Mandatory Fields with CSS3 Pseudo-Selectors

Datetime:2016-08-23 03:05:08          Topic: CSS3           Share

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:

:required{
border: 1px solid red;
}

Here’s what your final results should look like:

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.





About List