CSS :optional - Style Optional elements/inputs

The CSS :optional pseudo-class is used when we need to apply style to FORM elements (INPUT, SELECT, TEXTAREA), that are optional. For example:

HTML with CSS Code
<!DOCTYPE html>
<html>
<head>
   <style>
      input:optional {background-color: rosybrown; color: white;}
   </style>
</head>
<body>

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

Did You Notice ? Form element with no REQUIRED attribute is optional.

We can also use the :optional pseudo-class for SELECT and TEXTAREA FORM elements. For example:

HTML with CSS Code
<!DOCTYPE html>
<html>
<head>
   <style>
      select:optional, textarea:optional {background-color: rgb(31, 73, 73); color: white;}
   </style>
</head>
<body>

   <form>
      Select Course: <select>
         <option value="py">Python</option>
         <option value="cpp">C++</option>
         <option value="js">JavaScript</option>
      </select><br/><br/>
      Comment: <textarea rows="5" cols="40"></textarea><br/><br/>
      Username: <input type="text" required><br/>
      Password: <input type="password" required>
   </form>
   
</body>
</html>
Output
Select Course:

Comment:

Username:
Password:

CSS Online Test


« Previous Tutorial Next Tutorial »