CSS - Pseudo-class :optional



The CSS pseudo-class selector :optional is useful in selecting and styling form elements, such as <input>, <select> or <textarea>, that are not required or mandated for user input or you can say that does not have a required attribute set on it.

Accessibility concerns: When a form lists some optional <input> fields, it should clearly indicate the fields that are required, using the required attribute. This will be helpful for those, who are navigating using the assistive technology, such as a screen reader, to understand the required fields for a successful submission of a form.

Apart from the required attribute, the mandatory fields should also be indicated using some descriptive text or icon, so that the required information is conveyed more clearly.

Syntax

:optional {
   /* ... */ 
}

CSS :optional Example

Here is an example of :optional pseudo-class:

In the following example, :optional pseudo-class is applied on the input element, that are not given the required attribute. A 3px wide blue border css styling is applied to the input element that is optional.

<html>
<head>
<style>
   label {
      display: block;
      margin: 1px;
      padding: 1px;
   }

   .field {
      margin: 1px;
      padding: 1px;
   }

   input:optional {
      border-color: blue;
      border-width: 3px;
   }

   label.required::after {
      content: "*";
      color: red;
   }

   button {
      background-color: green;
      color: white;
   }

   form {
      border: 3px solid black;
   }
</style>
</head>
<body>
   <form>
      <div class="field">
         <label for="name" class="required">Name:</label>
         <input type="name" id="name" required/>
      </div>
      
      <div class="field">
         <label for="age">Age: (optional)</label>
         <input type="age" id="age" />
      </div>

      <div class="field">
         <label for="feedback">Feedback: (optional)</label>
         <input type="feedback" id="feedback" />
      </div>

      <div class="field">
         <button type="">Submit</button>
      </div>
   </form>
</body>
</html>
Advertisements