首页 > 代码库 > CSS-三角形及其原理

CSS-三角形及其原理

CSS中三角形在网页中比较常见,以前是图片,不过现在基本上都是通过CSS可以完成,实现比较简单,我们可以看一组简单的三角形效果:

技术分享

其实实现起来比较简单,通过空div然后设置宽高为0,之后可以四周border的宽度,控制三角形的形状,四个border可以看成是两横横竖的木头的重叠的效果,两横在两竖上面,三角形就是中间重叠的部分切分出来的,样式的代码如下:

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
.triangle {
    width: 0;
    height: 0;
    border-top: 20px solid #EEB422;
    border-right: 20px solid #C0FF3E;
    border-bottom: 20px solid #A020F0;
    border-left: 20px solid #7CFC00;
}
 
.triangle-up {
    width: 0;
    height: 0;
    border-right: 20px solid transparent;
    border-bottom: 40px solid #A020F0;
    border-left: 20px solid transparent;
}
 
.triangle-down {
    width: 0;
    height: 0;
    border-top: 40px solid #EEB422;
    border-right: 20px solid transparent;
    border-left: 20px solid transparent;
}
 
.triangle-left {
    width: 0;
    height: 0;
    border-top: 20px solid transparent;
    border-bottom: 20px solid transparent;
    border-left: 40px solid #7CFC00;
}
 
.triangle-right {
    width: 0;
    height: 0;
    border-top: 20px solid transparent;
    border-bottom: 20px solid transparent;
    border-right: 40px solid #C0FF3E;
}
 
.triangle-left-bottom {
    width: 0;
    height: 0;
    border-top: 40px solid transparent;
    border-left: 40px solid #7CFC00;
}
 
.triangle-right-bottom {
    width: 0;
    height: 0;
    border-top: 40px solid transparent;
    border-right: 40px solid #C0FF3E;
}

具体的html页面代码:

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
<div class="row">
    <span>四个三角</span>
    <div class="triangle">
    </div>
</div>
<div class="row">
    <span>上三角</span>
    <div class="triangle-up">
    </div>
</div>
<div class="row">
    <span>下三角</span>
    <div class="triangle-down">
    </div>
</div>
<div class="row">
    <span>左三角</span>
    <div class="triangle-left">
    </div>
</div>
<div class="row">
    <span>右三角</span>
    <div class="triangle-right">
    </div>
</div>
<div class="row">
    <span>左下角</span>
    <div class="triangle-left-bottom">
    </div>
</div>
<div class="row">
    <span>右下角</span>
    <div class="triangle-right-bottom">
    </div>
</div>

CSS-三角形及其原理