CSS Selector - CSS :required








The :required selector selects form elements with a required attribute.

Summary

CSS Version
3

CSS Syntax

:required {
   style properties 
}

Browser compatibility

:required Yes 10.0 Yes Yes Yes




Example

<!DOCTYPE html>
<html>
<head>
<style>
input:required {<!--from  ww w  .j  a  v  a  2 s. com-->
    background-color: red;
}
</style>
</head>
<body>

    <p>An optional input element:<br><input></p>
    
    <p>A required input element:<br><input required></p>


</body>
</html>

Click to view the demo





Example 2

The following code shows how to select required and optional input Elements.

<!DOCTYPE HTML>
<html>
<head>
<style>
:required {<!--from w w w .  j  av a2  s . c  o  m-->
  outline: medium solid green;
}

:optional {
  outline: medium solid red;
}
</style>
</head>
<body>
  <form method="post" action="http://example.com/form">
    <p>
      <label for="price1"> $ per unit in your area:
         <input type="number" min="0" max="100" required value="1" id="price1" name="price1" />
      </label>
      <label for="price2"> $ per unit in your area:
         <input type="number" min="0" max="100" value="1" id="price2" name="price2" />
      <input type="submit" value="Submit" />
      </label>
    </p>
  </form>
</body>
</html>

Click to view the demo