W3docs

CSS :required Pseudo Class

Use the :required CSS pseudo-class for selecting the elements that are required. Read about the pseudo-class and practice with examples.

The :required CSS pseudo-class selects form elements that have the required attribute set. This allows forms to indicate which fields must contain valid data before submission, helping users avoid unnecessary waiting.

It applies to form elements that support the required attribute, such as <input>, <select> and <textarea>. The :required selector can be linked with pseudo-elements (e.g. ::after) and other selectors (e.g. :hover). Non-required elements can be customized with the :optional pseudo class along with :valid and :invalid which are activated when a form field’s data requirements are met.

Version

W3C Selectors Level 4

CSS Basic User Interface Module Level 3

Syntax

CSS :required syntax

:required {
  css declarations;
}

Example of the :required selector:

CSS :required code example

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      .example {
        margin: 40px auto;
        max-width: 400px;
      }
      label,
      button {
        display: block;
        width: 100%;
        margin-bottom: 1.5em;
      }
      input,
      button {
        padding: .4em 1em;
      }
      input {
        border: 1px solid #666666;
      }
      input:optional {
        background-color: #eeeeee;
        color: #666666;
      }
      input:required {
        border-bottom: 3px solid #1c87c9;
      }
    </style>
  </head>
  <body>
    <h2>:required selector example</h2>
    <div class="example">
      <form action="#">
        <label>
          <input type="text" required />Name *
        </label>
        <label>
          <input type="email" required />Email *
        </label>
        <label>
          <input type="tel" />Phone (optional)
        </label>
        <label>
          <input type="url" />Address (optional)
        </label>
      </form>
    </div>
  </body>
</html>

In the given example both the :optional and the :required pseudo-class selectors are used.

Practice

Practice

What is the function of the ':required' pseudo-class in CSS?