# CSS `:checked` Pseudo-class

The `:checked` pseudo-class represents any **radio** (`<input type="radio">`), **checkbox** (`<input type="checkbox">`), or **option** (`<option>` in a `<select>`) element that is checked or toggled to an "on" state.

## 1. Basic Usage

You can use it to style the input element itself.

```css
input[type="checkbox"]:checked {
  accent-color: green; /* Sets the color of the checkbox/radio */
  outline: 2px solid green;
}
```

## 2. The "Checkbox Hack" (Custom UI)

The most powerful use of `:checked` is combining it with sibling selectors (`+` or `~`) to style *other* elements based on the input's state. This enables pure CSS interactive components like toggles, tabs, and modals.

### Example: Custom Toggle

**HTML:**
```html
<label class="toggle">
  <input type="checkbox">
  <span class="slider"></span>
</label>
```

**CSS:**
```css
/* Hide the actual input */
.toggle input {
  display: none;
}

/* Style the slider based on the input state */
.toggle input:checked + .slider {
  background-color: #2196F3;
}
```

## 3. Use Case: Pure CSS Accordion

Using a hidden checkbox to toggle visibility of a content panel.

**HTML:**
```html
<div class="accordion">
  <input type="checkbox" id="tab1">
  <label for="tab1">Click me</label>
  <div class="content">
    Hello World!
  </div>
</div>
```

**CSS:**
```css
/* Hide input and content initially */
input[type="checkbox"], .content {
  display: none;
}

/* Show content when checkbox is checked */
input:checked ~ .content {
  display: block;
}
```

## 4. `:checked` vs `[checked]`

*   **`:checked`**: Matches the **current live state**. Updates when the user interacts with the element.
*   **`[checked]`**: Matches the **HTML attribute**. Only checks if `checked` was present in the initial HTML (or added via JS `setAttribute`). It does *not* track user interaction.

**Always use `:checked` for styling state.**

[[programming/css/css]]
[[programming/css/pseudo-classes-and-pseudo-elements]]
[[programming/css/selectors]]