最近项目涉及到代金券的设计,下面介绍两种方法实现css锯齿效果

1.用dotted圆点边框覆盖p

html代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>css实现锯齿效果</title>
<link rel="stylesheet" href="./demo.css">
</head>
<body>
<div style="width:100%;height:500" class="block">
<div class="coupon sawtooth">

</div>
</div>
</body>
</html>

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
.coupon{
width: 300px;
height: 200px;
background: red;
margin: 0 auto;
}
.sawtooth {
/* 相对定位,方便让before和after伪元素绝对定位偏移 */
position: relative;
}

.sawtooth:before, .sawtooth:after {
content: ' ';
width: 0;
height: 100%;
/* 绝对定位进行偏移 */
position: absolute;
top: 10px;
}

.sawtooth:before {
/* 圆点型的border */
border-right: 10px dotted white;
/* 偏移一个半径,让圆点的一半覆盖p */
left: -5px;
}

.sawtooth:after {
/* 圆点型的border */
border-left: 10px dotted white;
/* 偏移一个半径,让圆点的一半覆盖p */
right: -5px;
}

效果图如下

使用before和after伪元素的border实现
使用before和after伪元素的border实现

这个方法有个问题,就是我在做iosApp的时候border-right: 10px dotted white;端上会出现方形的点,而不是圆形的点,这个很坑爹,所以建议用下一种方法,安卓跟ios都测试过没有那个问题

2.透明背景方法

这种方法的核心是使用css的radial-gradient的方法,该方法要求IE10以上的浏览器
html代码跟上面的一样,不用变化
css代码
首先先实现这种效果

css实现网状图
css实现网状图
1
2
3
4
5
6
7
8
9
10
11
12
13
14
.coupon{
width: 300px;
height: 200px;
background: red;
margin: 0 auto;
}
.sawtooth {
background-image: radial-gradient(transparent 0, transparent 5px, #e24141 5px);
background-size: 15px 15px;
background-position: 8px 3px;
/* 相对定位,让before伪元素方便定位 */
position: relative;
z-index: 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
25
26
27
28
29
30
.coupon{
width: 300px;
height: 200px;
background: white;
margin: 0 auto;
}
.sawtooth {
background-image: radial-gradient(transparent 0, transparent 5px, #e24141 5px);
background-size: 15px 15px;
background-position: 8px 3px;
/* 相对定位,让before伪元素方便定位 */
position: relative;
z-index: 1;
}

.sawtooth:before {
content: ' ';
display: block;
/* 用相同的颜色覆盖 */
background-color: #e24141;
/* 绝对定位,遮住中间所有的洞,只保留边角的锯齿 */
position: absolute;
top: 0;
bottom: 0;
/* 为锯齿保留的距离 */
left: 10px;
right: 10px;
/* 让背景图放到底下 */
z-index: -1;
}

参考方法: 点此链接