iOSのスイッチのような見た目をチェックボックスで作る機会があったので、実装方法をメモ。
サンプルコード
まずはHTMLです。
labelで見た目の実装をして、隣接セレクタでチェック時の切り替えを行うようにします。
<input type="checkbox" class="c-switch-check" id="check"> <label class="c-switch-label" for="check"></label>
checkboxは非表示にして、labelと擬似要素を使って見た目の設定をします。
.c-switch-check {
display: none;
}
.c-switch-label {
position: relative;
display: inline-block;
width: 50px;
height: 30px;
border-radius: calc(30px / 2);
background: #cccccc;
transition: background 200ms;
}
.c-switch-label::before {
content: '';
position: absolute;
top: 2px;
left: 2px;
display: block;
width: calc(30px - 4px);
height: calc(30px - 4px);
border-radius: calc((30px - 4px) / 2);
background: #ffffff;
transform: translateX(0);
transition: transform 200ms;
}
.c-switch-check:checked + .c-switch-label {
background: #3dcc55;
}
.c-switch-check:checked + .c-switch-label::before {
transform: translateX(calc((50px - 4px) - (30px - 4px)));
}
iOSのスイッチを実装するデモページ
calc()を使って各サイズや位置の設定を行なっているので、スイッチ自体のサイズを変更する場合は適宜調整してください。
コメントが承認されるまで時間がかかります。