css实现三角形是常见的需求,在此记录如下
原理:相邻的border之间会形成一条斜线(可按此联想记忆)
.triangle {
width: 0;
height: 0;
border-left: 100px solid red;
border-right: 100px solid green;
border-top: 100px solid blue;
border-bottom: 100px solid orange;
}
注意:相邻的border形成的斜线,斜线一定是相邻产生
1?
.triangle {
width: 0;
height: 0;
border-left: 100px solid transparent;
border-right: 100px solid transparent;
border-bottom: 100px solid orange;
}
2
.triangle {
width: 0;
height: 0;
border-left: 100px solid transparent;
border-right: 100px solid transparent;
border-bottom: 100px solid orange;
}
3
.triangle {
width: 0;
height: 0;
border-top: 100px solid transparent;
border-left: 100px solid orange;
}
.triangle {
width: 0;
height: 0;
border-right: 100px solid transparent;
border-bottom: 100px solid orange;
}
两种理解:橙色是左下,斜线在橙色的右上,因为要两两相邻,只能下如下两种搭配
或者
4
.triangle {
width: 0;
height: 0;
border-bottom: 100px solid transparent;
border-left: 100px solid orange;
}
.triangle {
width: 0;
height: 0;
border-right: 100px solid transparent;
border-top: 100px solid orange;
}
两种理解:橙色是左上,斜线在橙色的右下,因为要两两相邻,只能下如下两种搭配
或者
5
.triangle {
width: 0;
height: 0;
border-bottom: 100px solid transparent;
border-right: 100px solid orange;
}
.triangle {
width: 0;
height: 0;
border-left: 100px solid transparent;
border-top: 100px solid orange;
}
两种理解:橙色是右上,斜线在橙色的左下,因为要两两相邻,只能下如下两种搭配
或者
6
.triangle {
width: 0;
height: 0;
border-top: 100px solid transparent;
border-right: 100px solid orange;
}
.triangle {
width: 0;
height: 0;
border-left: 100px solid transparent;
border-bottom: 100px solid orange;
}
两种理解:橙色是右下,斜线在橙色的左上,因为要两两相邻,只能下如下两种搭配
或者
原理:通过控制linear-gradient线性渐变角度和渐变距离(其实不是渐变,是拼色),使得从矩形一个角开始形成三角形
.triangle {
width: 100px;
height: 100px;
background: linear-gradient(45deg, red, red 50%, orange 50%, orange);
}
当把第二种颜色设置为透明时:
.triangle {
width: 100px;
height: 100px;
background: linear-gradient(45deg, red, red 50%, transparent 50%, transparent);
}
原理:通过clip-path,传递多边形路径坐标形成三角形
.triangle {
width: 100px;
height: 100px;
background: orange;
clip-path: polygon(0 0,100% 0, 100% 100%);