概要
チェックボックスを使って、CSSだけでトグルボタン(トグルスイッチ)を作る方法です。
Javascriptを実装せずに作成することが可能です。
サンプル
See the Pen toggle-css by take it easy (@take-it-easy) on CodePen.
コーディング方法
HTML
<div class="toggle-area">
<div class="item">
<input type="checkbox" id="sample-1" name="toggle1" value="1">
<label for="sample-1">トグルボタン1</label>
</div>
<div class="item">
<input type="checkbox" id="sample-2" name="toggle2" value="2">
<label for="sample-2">トグルボタン2</label>
</div>
<div class="item">
<input type="checkbox" id="sample-3" name="toggle3" value="3">
<label for="sample-3">トグルボタン3</label>
</div>
</div>
CSS
div.item {
margin: 15px;
}
div.toggle-area input[type="checkbox"] {
display: none;
}
label {
position: relative;
padding-left: 60px;
cursor: pointer;
}
label::before,
label::after {
content: "";
display: block;
position: absolute;
/* 位置調整 */
top: 50%;
left: 0px;
/* 中央に揃える */
transform: translateY(-50%);
/* 枠線 */
border: 1.4px solid rgba(0,0,0,.3);
border-radius: 50%;
/* アニメーションの変化時間 */
transition: .2s;
}
label::before {
/* 背景色 */
background-color: rgba(0, 106, 182, .2);
/* 枠線 */
border: 1.4px solid rgba(0,0,0,.3);
border-radius: 12px;
/* サイズ調整 */
height: 20px;
width: 40px;
/* 位置調整 */
top: 50%;
left: 5px;
}
label::after {
/* 背景色 */
background-color: #fff;
/* 枠線 */
border-radius: 50%;
/* サイズ調整 */
height: 23px;
width: 23px;
/* 位置調整 */
top: 50%;
left: 0px;
}
/* チェックありの場合 */
input:checked + label::before {
/* 背景色 */
background-color: rgb(0, 106, 182);
}
input:checked + label::after {
/* トグルを右に移動させる */
left: 26px;
}