CSS Reference Pseudo-class

:required

:required is a CSS pseudo-class selector used to select form elements that are required.

More specifically, it is used to select form elements that have the required attribute set.

The form elements than can be selected using :required are <input>s, <select>s, and <textarea>s without a required attribute.

For example, the following form elements can be selected using :required:

<input type="name" required>

<input type="checkbox" required>

<input type="email" required>

<!-- and other input types as well.. -->

<textarea name="name" id="message" cols="30" rows="10" required></textarea>

<select name="nm" id="sel" required>
    <!-- options -->
</select>
                

The following form elements can not be selected using :required because they don’t have the required attribute set:

<input type="text">

<input type="submit">

<!-- and other input types as well.. -->

<textarea name="name" id="id" cols="30" rows="10"></textarea>

<select name="nm" id="sel">
    <!-- options -->
</select>
                

:required is useful for styling required form elements to provide more visual focus on them so that the user knows that they are required and should be filled.

Trivia & Notes

If you want to select form elements that are optional, you can use the :optional pseudo-class selector.

Just like other pseudo-class selectors, the :required selector can be chained with other selectors such as :hover and with pseudo-elements such as ::after, among others. For example, the following rule will provide :focus styles for a required text area:

textarea:required:focus {
    /* content and styles here */
}
                

Examples

The following will apply a red border to an email input field. This field is usually required in contact forms so that the owner of the website can reply back to whoever submitted the form.

input[type="email"]:required {
    border:2px solid tomato;
}
                

The following will apply a red color to the labels of required input fields (as long as the label comes right after the input in the source order):

input:required + label {
    color: tomato;
    font-weight: bold;
}
                

Live Demo

In the following demo, both the :requiredand the :optional pseudo-class selectors are used to style form elements that are optional and required, respectively, to make required forms stand out visually.

View this demo on the Codrops Playground

Browser Support

The :optional pseudo-class selector is supported in Chrome 10+, Firefox, Safari, Opera 10+, Internet Explorer 10+, and on Android and iOS.

Written by . Last updated February 3, 2015 at 12:33 pm by Manoela Ilic.

Do you have a suggestion, question or want to contribute? Submit an issue.