標準のチェックボックスを、モダンで美しいトグルスイッチに置き換えるスニペットです。CSSの疑似要素と :checked 疑似クラスを利用し、JavaScriptなしで滑らかなアニメーションを実現しています。
<label class="custom-toggle">
<input type="checkbox" class="custom-toggle-input" aria-label="Toggle Switch" />
<span class="custom-toggle-slider"></span>
</label>/* トグルスイッチのコンテナ */
.custom-toggle {
position: relative;
display: inline-block;
width: 60px;
height: 34px;
}
/* デフォルトのチェックボックスを隠す */
.custom-toggle-input {
opacity: 0;
width: 0;
height: 0;
}
/* スライダーの背景 */
.custom-toggle-slider {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #e2e8f0;
transition: background-color 0.4s;
border-radius: 34px;
box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.1);
}
/* スライダーのつまみ部分 */
.custom-toggle-slider:before {
position: absolute;
content: "";
height: 26px;
width: 26px;
left: 4px;
bottom: 4px;
background-color: white;
transition: transform 0.4s cubic-bezier(0.68, -0.55, 0.265, 1.55);
border-radius: 50%;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}
/* チェック時の背景色 */
.custom-toggle-input:checked + .custom-toggle-slider {
background-color: #3b82f6;
}
/* キーボードフォーカス時のアウトライン */
.custom-toggle-input:focus-visible + .custom-toggle-slider {
outline: 2px solid #3b82f6;
outline-offset: 2px;
}
/* チェック時のつまみの移動 */
.custom-toggle-input:checked + .custom-toggle-slider:before {
transform: translateX(26px);
} ネイティブの <input type="checkbox"> はブラウザごとにスタイリングが異なり、カスタマイズの自由度が低いため、このスニペットではチェックボックスそのものを非表示にし、隣接する <span> 要素(スライダー)を使って見た目を構築しています。
opacity: 0 と幅・高さを 0 にすることで、機能は保ちつつ画面から見えなくしています。::before 疑似要素を使って円形の「つまみ」部分を作成しています。transition: transform 0.4s cubic-bezier(0.68, -0.55, 0.265, 1.55) を指定することで、つまみが移動する際に少しバウンドするような心地よいアニメーション(イージング)を実現しています。:focus-visible を使ってアウトラインを表示するようにしています。このトグルスイッチは、設定画面やダークモードの切り替えなど、直感的なオン/オフ操作が求められる場面で活躍します。