示例


HTML 原始碼


1
2
3
4
5
6
<label for="toggle">
<input type="checkbox" id="toggle">
<span id="button">
<div class="button-body"></div>
</span>
</label>

CSS 原始碼


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
:root {
--button-width: 500px;
--button-height: 295px;
--toggle-diameter: 255px;
--button-toggle-offset: calc((var(--button-height) - var(--toggle-diameter)) / 2);
--toggle-shadow-offset: 10px;
--toggle-wider: 333px;
--color-grey: #E9E9E9;
--color-green: #30D158;
}

#button {
display: inline-block;
width: var(--button-width);
height: var(--button-height);
background-color: var(--color-grey);
border-radius: calc(var(--button-height) / 2);
position: relative;
transition: .3s all ease-in-out;
}

#button::after {
content: '';
display: inline-block;
width: var(--toggle-diameter);
height: var(--toggle-diameter);
background-color: #fff;
border-radius: calc(var(--toggle-diameter) / 2);
position: absolute;
top: var(--button-toggle-offset);
transform: translateX(var(--button-toggle-offset));
box-shadow: var(--toggle-shadow-offset) 0 calc(var(--toggle-shadow-offset) * 4) rgba(0, 0, 0, .10);
transition: .3s all ease-in-out;
}

.button-body {
display: flex;
justify-content: center;
align-items: center;
min-height: 25vh;
}

input[type="checkbox"]:checked + #button {
background-color: var(--color-green);
}

input[type="checkbox"]:checked + #button::after {
transform: translateX(calc(var(--button-width) - var(--toggle-diameter) - var(--button-toggle-offset)));
box-shadow: calc(var(--toggle-shadow-offset) * -1) 0 calc(var(--toggle-shadow-offset) * 4) rgba(0, 0, 0, .10);
}

input[type="checkbox"] {
display: none;
}

input[type="checkbox"]:active + #button::after {
width: var(--toggle-wider);
}

input[type="checkbox"]:checked:active + #button::after {
transform: translateX(calc(var(--button-width) - var(--toggle-wider) - var(--button-toggle-offset)));
}