CSS :checked - Apply Styles When Checkbox/Radio Checked

CSS :checked - Apply Styles When Checkbox/Radio Checked

  • CSS
  • 3 mins read

Introduction

The :checked pseudo-class in CSS selects elements that are in a checked state, such as checkboxes or radio buttons. This allows you to apply specific styles to elements when they are selected by the user.

Example 1: Styling a Checkbox

In this example, the CSS selector input[type=checkbox]:checked selects the checkbox when it is in a checked state. The accent-color property is then used to change the color of the checkbox to red when the checkbox is selected.

HTML Code:

<label>
  <input type="checkbox" name="example-checkbox" id="example-checkbox">
  I accept the terms and conditions
</label>

CSS Code:

input[type=checkbox]:checked {
  accent-color: red;
}

Output:

See the Pen :checked ex1 by Vinish Kapoor (@foxinfotech) on CodePen.

Example 2: Styling a Group of Radio Buttons

In this example, the CSS selector input[type=radio]:checked selects the radio button when it is in a checked state. The accent-color property is then used to change the color of the checkbox to red when the radio button is selected.

HTML Code:

<form>
  <label>
    <input type="radio" name="example-radio" value="option-1" checked>
    Option 1
  </label>
  <label>
    <input type="radio" name="example-radio" value="option-2">
    Option 2
  </label>
  <label>
    <input type="radio" name="example-radio" value="option-3">
    Option 3
  </label>
</form>

CSS Code:

input[type=radio]:checked {
  accent-color: red;
}

Output:

See the Pen :checked ex-2 by Vinish Kapoor (@foxinfotech) on CodePen.

Browser Support

Conclusion

The :checked pseudo-class in CSS allows you to apply specific styles to elements when they are selected by the user. This can be used to create more interactive and engaging user interfaces. Remember, the color property doesn't work with checkbox and radio buttons but accent-color property is a good alternative.

FAQ

What is the :checked pseudo-class in CSS?

The :checked pseudo-class in CSS is a way to select elements that are in a checked state, such as checkboxes or radio buttons. This allows you to apply specific styles to elements when they are selected by the user.

How do I use the accent-color property with checkboxes and radio buttons?

The accent-color property can be used as an alternative to the color property when styling checkboxes and radio buttons. You can use the :checked pseudo-class in CSS to select the element when it's in a checked state and then apply the accent-color property to change the color of the element.

Can I style the label of a checkbox or radio button using the :checked pseudo-class?

The :checked pseudo-class in CSS only selects the checkbox or radio button itself, not the label associated with it. To style the label, you can use CSS selectors such as input:checked + label to select the label immediately following the selected checkbox or radio button.