CSS :required - Style Required Field

The CSS :required pseudo-class is used when we need to style FORM ELEMENTS having the REQUIRED attribute. For example:

HTML with CSS Code
<!DOCTYPE html>
<html>
<head>
   <style>
      input:required {background-color: #ccc; padding: 6px; font-weight: bold;}
   </style>
</head>
<body>

   <form>
      Username: <input type="text" required><br/><br/>
      Email ID: <input type="email"><br/><br/>
      Password: <input type="password" required><br/><br/>
   </form>
   
</body>
</html>
Output
Username:

Email ID:

Password:

The "style" tag specifies the CSS rules that will be applied to form elements. The selector "input:required" is used to target form elements with the required attribute set. It will select the "Username" and "Password" input fields in this case.

The CSS properties that follow the selector are then applied to the elements that have been selected. In this case, the input fields' background color will be gray (#ccc), and the text within the input fields will be bolded. In addition, 6 pixels of padding will be added to the input fields to give them more space.

Because the "Email ID" input field lacks the required attribute, the CSS rules defined in the code will have no effect on it.

We can easily style required form elements to make them stand out and provide visual cues to users by using the :required class. This can help to improve form user experience and make it easier for users to understand which fields are required.

CSS :required syntax

The general form of the ":required" class in CSS is:

input:required {
   // CSS styles to apply when the input is required
}

In the preceding syntax, "input" refers to the form element to which the styles should be applied, and ":required" is the pseudo-class that targets input elements with the required attribute set. Depending on which element we want to style, we can replace input with other form elements such as textarea, select, and so on.

Advantages of the ":required" class in CSS

Disadvantages of the ":required" class in CSS

CSS Online Test


« Previous Tutorial Next Tutorial »


Liked this post? Share it!