CSS - Pseudo-class :checked



The CSS pseudo-class selector :checked represents any checkbox (<input type="checkbox">), radio (<input type="radio">), or option (<option> in a <select>) element that is either checked or toggled to the on state.

This state can be engaged or disengaged, by either checking/selecting or unchecking/deselecting the element.

Syntax

:checked {
   /* ... */
}

CSS :checked Example

Here is an example of :checked pseudo-class for radio button. When the radio button is selected or checked, the box-shadow styling is applied around the selected radio button.

<html>
<head>
<style>
   div {
      margin: 10px;
      padding: 10px;
      font-size: 20px;
      border: 3px solid black;
      width: 200px;
      height: 45px;
      box-sizing: border-box;
   }

   input[type="radio"]:checked {
      box-shadow: 0 0 0 8px red;
   }
</style>
</head>
<body>
   <h2>:checked example - radio</h2>
   <div>
      <input type="radio" name="my-input" id="yes">
      <label for="yes">Yes</label>
      <input type="radio" name="my-input" id="no">
      <label for="no">No</label>
   </div>
</body>
</html>

Here is an example of :checked pseudo-class for checkbox. When the checkbox is checked, the box-shadow styling along with the color and border styling applies on the checkbox and its label.

<html>
<head>
<style>
   div {
      margin: 10px;
      font-size: 20px;
   }

   input:checked + label {
      color: royalblue;
      border: 3px solid red;
      padding: 10px;
   }

   input[type="checkbox"]:checked {
      box-shadow: 0 0 0 6px pink;
   }
</style>
</head>
<body>
   <h2>:checked example - checkbox</h2>
   <div>
      <p>Check and uncheck me to see the change</p>
      <input type="checkbox" name="my-checkbox" id="opt-in">
      <label for="opt-in">Check!</label>
   </div>
</body>
</html>

Here is an example of :checked pseudo-class for option. When an option is selected from the list, the background color changes to lightyellow and font-color changes to red.

<html>
<head>
<style>
   select {
      margin: 10px;
      font-size: 20px;
   }

   option:checked {
      background-color: lightyellow;
      color: red;
   }
</style>
</head>
<body>
   <h2>:checked example - option</h2>
   <div>
   <h3>Ice cream flavors:</h3>
      <select name="sample-select" id="icecream-flav">
         <option value="opt3">Butterscotch</option>
         <option value="opt2">Chocolate</option>
         <option value="opt3">Cream n Cookie</option>
         <option value="opt3">Hazelnut</option>
         <option value="opt3">Roasted Almond</option>
         <option value="opt1">Strawberry</option>
      </select>
   </div>   
</body>
</html>
Advertisements