Checked CSS Selector

Learn via video course
FREE
View all courses
JavaScript Course With Certification: Unlocking the Power of JavaScript
JavaScript Course With Certification: Unlocking the Power of JavaScript
by Mrinal Bhattacharya
1000
4.8
Start Learning
JavaScript Course With Certification: Unlocking the Power of JavaScript
JavaScript Course With Certification: Unlocking the Power of JavaScript
by Mrinal Bhattacharya
1000
4.8
Start Learning
Topics Covered

How to Use the CSS Checked Selector?

The :checked CSS pseudo-class selector is used to select or deselect an already selected element for styling them.

We can use it with the help of checkbox element(<input type="checkbox">),option element (<option> in a <select>) and radio element(<input type="radio">).

Syntax

The general syntax is as follows

Examples

Example 1: Basic Example of CSS :checked

In this example we will be applying :checked CSS pseudo-class selector to style a checkbox element(<input type=“checkbox”>), option element (<option> in a <select>) and radio element(<input type="radio">).

Output CHECKED CSS

Example 2: Toggling Elements with a Hidden Checkbox

In this example, we will be using a hidden checkbox that can be used to toggle an element.

We can use the hidden property to hide the checkbox, and with the help of the <label>, we can control the toggle functionality.

Then we can use the adjacent sibling combinator to style the differently based on the state of the input.

Output

When checkbox is checked and we click on the toggle button.

TOGGLING ELEMENTS TOGGLE

When checkbox is checked and we click on the Toggle button.

TOGGLE

Note: By default the checkbox is unchecked in the above code snippet.

Explicit Styling Unchecked Elements

We can combine the :not pseudo-class with to explicitly style the unchecked elements like we use :checked CSS pseudo-class selector to style the checked(selected) elements. This can be useful if there are certain styles that we don’t want to see applied to the checked state.

For example, in the code snippet, we have used the explicit style to unchecked elements and gave them a red color.

Output

EXPLICIT STYLING

Browser Support

The following browsers fully supports the CSS pseudo-class selector:

CHECKED

Conclusion

  • :checked is a pseudo-class selector that’s used to style the checked state of radio, checkbox, or option elements.
  • We can hide the checkbox and can still toggle its value on and off by clicking the
  • the :not pseudo-class with :checked can be used to explicitly style unchecked elements.