Fork me on GitHub

自定义单选框复选框

我们都知道原生的复选框控件样式极难自定义,这对于工程师实现设计稿的难度加大了一大截。css3的出现,增加了:checked选择器,因此我们可以利用:checked和label来实现各式各样的表单选择控件,接下来让我们来看看如何实现吧!

程序员必读

Css3编码技巧

1.自定义复选框

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
.checkbox{
position: absolute;
clip: rect(0,0,0,0);
}

.checkbox[type="checkbox"] + label::before{
content: '\a0'; /* 不换行空格 */
display: inline-block;
margin-right: .3em;
width: 2em;
height: 2em;
border-radius: .3em;
vertical-align: middle;
line-height: 2em; /* 关键 */
font-size: 20px;
text-align: center;
color: #fff;
background: gray;
}

.checkbox[type="checkbox"]:checked + label::before{
content: '\2713'; /* 对勾 */
background: black;
}

2.自定义开关

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
63
64
65
66
67
68
/* 1 */
.switch{
position: absolute;
clip: rect(0,0,0,0);
}

.switch[type="checkbox"] + label{
width: 6em;
height: 3em;
padding: .3em;
border-radius: .3em;
border: 1px solid rgba(0,0,0,.2);
vertical-align: middle;
line-height: 2em; /* 关键 */
font-size: 20px;
text-align: center;
color: #fff;
box-shadow: 0 1px white inset;
background-color: #ccc;
background-image: linear-gradient(#ddd,#bbb);
}

.switch[type="checkbox"]:checked + label{
box-shadow: 0.05em .1em .2em rgba(0,0,0,.6) inset;
border-color: rgba(0,0,0,.3);
background: #bbb;
}

/* 2 */
.switch-an{
position: absolute;
clip: rect(0,0,0,0);
}

.switch-an[type="checkbox"] + label{
position: relative;
display: inline-block;
width: 5em;
height: 2em;
border-radius: 1em;
color: #fff;
background: #06c;
text-align: left;
}

.switch-an[type="checkbox"] + label::before{
content: '';
width:2em;
height: 2em;
position: absolute;
left: 0;
border-radius: 100%;
vertical-align: middle;
background-color: #fff;
transition: left .3s;
}
.switch-an[type="checkbox"] + label::after{
content: 'OFF';
margin-left: 2.6em;
}
.switch-an[type="checkbox"]:checked + label::before{
transition: left .3s;
left: 3em;
}
.switch-an[type="checkbox"]:checked + label::after{
content: 'NO';
margin-left: .6em;
}
Mr XuJiang wechat
欢迎您扫一扫上面的微信二维码,小猪送你啦!
0%