The :checked
pseudo-class in CSS is used to select and style form elements like radio buttons, checkboxes, and options in a select element that are in a selected or "checked" state. This allows you to provide visual feedback to users when they interact with these input types.
Example 1: Styling a Checked Checkbox
/* This CSS rule targets a checkbox input when it is checked. */
input[type="checkbox"]:checked {
/* The box-shadow property adds a blue glow around the checkbox. */
box-shadow: 0 0 5px 2px dodgerblue;
}
Explanation
This code applies a blue shadow around a checkbox when the user clicks on it. The input[type="checkbox"]
part selects all checkboxes, and the :checked
pseudo-class narrows that down to only the one that is currently checked.
Example 2: Revealing Content When a Radio Button is Checked
/* This CSS hides a div by default. */
.hidden-content {
display: none;
}
/* When the radio button with the id 'show' is checked, the adjacent .hidden-content div is displayed. */
#show:checked ~ .hidden-content {
display: block;
}
Explanation
This example demonstrates how to show a hidden element when a specific radio button is selected. The ~
is the general sibling combinator, which selects the .hidden-content
div that follows the checked radio button.
Example 3: Changing the Label Style of a Checked Option
/* This CSS rule targets the label of a checked radio button. */
input[type="radio"]:checked + label {
/* The color property changes the text color to green. */
color: green;
/* The font-weight property makes the text bold. */
font-weight: bold;
}
Explanation
This code changes the text color and weight of a label associated with a radio button when that button is selected. The +
is the adjacent sibling combinator, selecting the label that immediately follows the checked radio button.
Example 4: Custom Styled Checkbox
/* This CSS creates a custom styled checkbox. */
.custom-checkbox:checked {
background-color: #2196F3; /* Blue background when checked */
border-color: #2196F3;
}
.custom-checkbox:checked::before {
content: '\2713'; /* Adds a checkmark character */
display: block;
color: white;
text-align: center;
}
Explanation
This CSS provides a more customized look for a checkbox. When the checkbox is checked, its background color changes, and a checkmark character is inserted using the ::before
pseudo-element.
Example 5: Highlighting a selected option in a dropdown
/* This rule styles the selected option within a select element. */
option:checked {
background: linear-gradient(to right, #66bb6a, #43a047); /* Green gradient background */
color: white; /* White text color */
}
Explanation
This code enhances the user experience of a dropdown menu by styling the currently selected <option>
. It applies a green gradient background and white text to the option that has been :checked
.