# トグルスイッチのCSSアニメーション実装

> iOS風のオン/オフスイッチ。checkbox+擬似要素+transitionの組み合わせで、ノブの移動に弾みを付けます。

- カテゴリ: マイクロインタラクション
- URL: https://www.css-dictionary.com/animations/toggle-switch/

## HTML

```html
<label class="switch">
  <input type="checkbox">
  <span class="track" aria-hidden="true"></span>
  通知を受け取る
</label>
```

## CSS

```css
.switch {
  display: flex;
  align-items: center;
  gap: 10px;
  font-size: 14px;
  cursor: pointer;
  user-select: none;
}

.switch input {
  position: absolute;
  opacity: 0;
}

.track {
  position: relative;
  width: 52px;
  height: 30px;
  border-radius: 15px;
  background: #cec2a8;
  transition: background 0.25s ease;
  flex-shrink: 0;
}

.track::after {
  content: '';
  position: absolute;
  top: 3px;
  left: 3px;
  width: 24px;
  height: 24px;
  border-radius: 50%;
  background: #fff;
  box-shadow: 0 1px 3px rgb(0 0 0 / 0.25);
  transition: translate 0.25s cubic-bezier(0.2, 0.7, 0.3, 1.2);
}

.switch input:checked + .track {
  background: #527f5e;
}

.switch input:checked + .track::after {
  translate: 22px 0;
}

.switch input:focus-visible + .track {
  outline: 2px solid #c2452f;
  outline-offset: 2px;
}
```

## 仕組みの解説

checkboxはdisplay: noneではなくopacity: 0で「見えないが存在する」状態にしています（キーボードフォーカスを受けられるように）。ノブの移動はleftではなくtranslateで行い、少しオーバーシュートするcubic-bezierで「カチッ」とした手応えを演出します。:focus-visible時のoutlineをトラック側に描くことで、キーボード操作でも現在位置が分かります。

## 実装のポイント

実務ではrole="switch"とaria-checkedの利用も検討してください。フォーム部品の色だけ変えたい場合はaccent-colorという1行の選択肢もあります。

## 使っているプロパティ

- [transition](https://www.css-dictionary.com/property/transition.md)
- [transform](https://www.css-dictionary.com/property/transform.md)
- [border-radius](https://www.css-dictionary.com/property/border-radius.md)
- [pseudo-focus-visible](https://www.css-dictionary.com/property/pseudo-focus-visible.md)
- [outline](https://www.css-dictionary.com/property/outline.md)

