【前端】CSS进阶(绘制三角形)
Dandelion 10/1/2022 CSS
# 概述
# 实现原理
边框是实现三角形的关键,边框实际上并不是一条直线,如果将四条边设置不同的颜色,将边框逐渐放大,可以得到每条边框都是一个梯形
- 当分别取消边框的时候,发现下面几种情况:
- 取消一条边时,与这条边相邻的两条边的接触部分会变成直的
- 当仅有邻边时, 两个边会变成对分的三角
- 当保留边没有其他接触时,极限情况所有东西都会消失
- 通过上述变化规则,利用旋转、隐藏,以及设置内容宽高等属性,就能够实现其他类型的三角形
# 三角形的绘制
无边框的三角形(完全填充)
- 原理:border + transparent
.border_1 { width: 0; height: 0; border-style: solid; border-width: 0 50px 50px 50px; border-color: transparent transparent #d9534f transparent; } .border_2 { width: 0; height: 0; border-style: solid; border-width: 50px 0 0 50px; border-color: #d9534f transparent transparent transparent; } .border_3 { width: 0; height: 0; border-style: solid; border-width: 50px 50px 50px 50px; border-color: transparent #d9534f transparent transparent; }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23带边框的三角形(区分边框)
- 原理:两个完全填充的三角形重叠
.border_4 { width: 0; height: 0; border-style: solid; border-width: 0 50px 50px 50px; border-color: transparent transparent #d9534f transparent; position: relative; } .border_4::after { content: ''; border-style: solid; border-width: 0 40px 40px 40px; border-color: transparent transparent #96ceb4 transparent; position: absolute; top: 6px; left: -40px; }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# 三角形的变换
线性渐变:
linear-gradient()
.border_5 { display: inline-block; height: 50px; width: 50px; background: linear-gradient( 45deg, blue, blue 50%, transparent 50%, transparent 100% ); }
1
2
3
4
5
6
7
8
9
10
11
12锥形渐变:
conic-gradient()
.border_6 { display: inline-block; height: 100px; width: 100px; background: conic-gradient( from 90deg at 0 0, blue 0, blue 45deg, transparent 45.1deg ); }
1
2
3
4
5
6
7
8
9
10
11旋转:
transform: rotate
.border_7 { display: inline-block; height: 100px; width: 141px; position: relative; overflow: hidden; } .border_7::after { content: ''; position: absolute; left: 0; top: 0; right: 0; bottom: 0; background: blue; transform-origin: 0 0; transform: rotate(45deg); }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18裁剪元素的可视区域:
clip-path
.border_8 { display: inline-block; height: 100px; width: 100px; background: blue; clip-path: polygon(0 0, 100% 0, 0 100%, 0 0); }
1
2
3
4
5
6
7使用特殊字符
<div class=".border_9">◄</div> <div class=".border_9">►</div> <div class=".border_9">▼</div> <div class=".border_9">▲</div> <div class=".border_9">⊿</div> <div class=".border_9">△</div>
1
2
3
4
5
6.border_9 { font-size: 100px; color: blue; }
1
2
3
4