CSS :required Pseudo Clas

CSS :required Pseudo Clas

CSS :required Pseudo Clas


The :required selector selects those elements that are required. The :required selector selects form elements that have the required attribute set. Before submission forms can indicate which fields should have valid data which allows the user to avoid the unnecessary weight.

It only applies to the form elements <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

:required {
  css declarations;
}

Example of the: required selector:

<!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,
      select,
      button {
        padding: .4em 1em;
      }
      input,
      select {
        border: 1px solid #666666;
      }
      input:optional,
      select:optional {
        background-color: #eeeeee;
        color: #666666;
      }
      input:required,
      textarea:required {
        border-bottom: 3px solid #1c87c9;
      }
    </style>
  </head>
  <body>
    <h2>:required selector example</h2>
    <div class="example">
      <form action="#">
        <label>
          <input type="name" required>Name *
        </label>
        <label>
          <input type="email" required>Email *
        </label>
        <label>
          <input type="phone">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.

Reactions

Post a Comment

0 Comments

close