CSS :checked Pseudo Class

CSS :checked Pseudo Class

CSS :checked Pseudo-Class

The :checked pseudo-class applies styles to checkboxes, radio buttons, and switches when they are selected (checked).

1. Basic Usage

✅ Styling a Checked Checkbox

input[type="checkbox"]:checked { background-color: green; border: 2px solid green; }

✅ Changes the background color of a checked checkbox.

2. Styling a Checked Radio Button

input[type="radio"]:checked { outline: 2px solid blue; }

✅ Adds a blue outline to a selected radio button.

3. Showing & Hiding Elements Based on Check State

✅ Show a Message When Checkbox is Checked

#message { display: none; } input[type="checkbox"]:checked ~ #message { display: block; color: green; }

✅ The message appears only when the checkbox is checked.

<input type="checkbox" id="toggle"> <label for="toggle">Check me</label> <p id="message">✅ Checkbox is checked!</p>

4. Creating a Custom Toggle Switch

.switch { position: relative; width: 50px; height: 25px; background: gray; border-radius: 25px; cursor: pointer; } .switch input { display: none; } .switch::before { content: ""; position: absolute; width: 20px; height: 20px; background: white; border-radius: 50%; top: 2.5px; left: 3px; transition: 0.3s; } input:checked + .switch::before { left: 25px; background: green; }

✅ A toggle switch effect using :checked.

<input type="checkbox" id="toggle-switch"> <label for="toggle-switch" class="switch"></label>

5. When to Use :checked?

Custom checkboxes and radio buttons
Toggling UI elements dynamically
Building interactive forms without JavaScript

Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close