用纯CSS来画一个checkbox

不使用图片,使用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

input[type=checkbox] {
width: 0;
height: 0;
margin: 0 6px 0 6px;
}

input[type=checkbox]::before {
content: "";
display: block;
position: absolute;
left: 10px;
top: 1px;
width: 15px;
height: 15px;
text-align: center;
line-height: 14px;
font-size: 16px;
color: #fff;
border: 2px solid #ddd;
background-color: #fff;
box-sizing: border-box;
}

input[type=checkbox]:checked::before {
content: "";
display: block;
position: absolute;
left: 10px;
top: 1px;
width: 15px;
height: 15px;
text-align: center;
line-height: 14px;
font-size: 16px;
color: #fff;
border: 2px solid green;
background-color: green;
box-sizing: border-box;
}

input[type=checkbox]:checked:after {
content: "L";
display: block;
position: absolute;
left: 10px;
top: 1px;
width: 15px;
height: 15px;
text-align: center;
line-height: 14px;
font-size: 14px;
transform: matrix(-0.766044, -0.642788, -0.642788, 0.766044, 0, 0);
-webkit-transform: matrix(-0.766044, -0.642788, -0.642788, 0.766044, 0, 0);
border-color: green;
color: #fff;
}

思路

  1. 先隐藏掉默认勾选框的样式
  2. 使用伪类:before构造默认选框的样式,记得和调整位置和默认选框位置一致
  3. 使用伪类:after构造勾选之后的样式, content里用反转旋转后的L字母来作为打钩的样式

预览结果

image