CSS :required
selector is used to select and style the form elements that have a required
attribute. In case you don’t know, the required
attribute indicates to the user which fields are necessary to fill out before submission.
The :required selector only applies to the <input>, <select> and the <textarea> elements.
The :required
selector in the following example sets a red color border to those <input>
elements that have a required attribute:
Example:
input:required{ border-color: red; }
The :required
selector in the following example selects all <textarea>
elements with a required attribute and sets a red color border around them:
Example:
textarea:required{ border-color: red; }
The :required
selector can also be used with other pseudo-class as well as pseudo-element selectors. It means that we can select all required elements and add styles to them on hover, focus, active, etc.
In the following example, we are applying a red color border to the <input> elements that have a required attribute only when we are hovering over them:
Example:
input:required:hover{ border-color: red; }
CSS Syntax
The syntax of the :required
selector is as follows:
:required{ CSS Styles; }
Browser Support
The number in each cell of the table specifies the first version of the browser that fully supports the :required
selector.
Selector | |||||
:required | 10.0 | 10.0 | 4.0 | 5.0 | 10.0 |