:required 5q4zx
:required is a CSS pseudo-class selector used to select form elements that are required. 6o3j6h
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 knows that they are required and should be filled.
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 :focus
styles for a required text area:
textarea:required:focus { /* content and styles here */ }
Examples 3y6d6i
The following will apply a red border to an email input field. This field is usually required in 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 176n59
In the following demo, both the :required
and the :optional
pseudo-class selectors are used to style form elements that are optional and required, respectively, to make required forms stand out visually.
Browser s162l
The :optional
pseudo-class selector is ed in Chrome 10+, Firefox, Safari, Opera 10+, Internet Explorer 10+, and on Android and iOS.