css如何制作三角形
使用边框属性制作三角形
通过设置元素的宽度和高度为0,利用边框属性可以创建三角形。边框的交汇处会形成斜边,通过设置不同边的颜色和透明度实现三角形效果。
.triangle {
width: 0;
height: 0;
border-left: 50px solid transparent;
border-right: 50px solid transparent;
border-bottom: 100px solid red;
}
调整三角形方向
修改边框属性可以改变三角形的方向。例如,将border-bottom改为border-top,三角形会朝下。
.triangle-up {
border-left: 50px solid transparent;
border-right: 50px solid transparent;
border-bottom: 100px solid blue;
}
.triangle-down {
border-left: 50px solid transparent;
border-right: 50px solid transparent;
border-top: 100px solid green;
}
创建直角三角形
通过设置部分边框为透明,可以创建直角三角形。例如,只设置左边框和下边框。

.right-triangle {
width: 0;
height: 0;
border-left: 100px solid red;
border-bottom: 100px solid transparent;
}
使用clip-path制作三角形
clip-path属性提供更灵活的图形裁剪方式,可以直接绘制三角形。
.clip-triangle {
width: 100px;
height: 100px;
background-color: purple;
clip-path: polygon(50% 0%, 0% 100%, 100% 100%);
}
使用伪元素生成三角形
通过伪元素结合边框属性,可以在其他元素上添加三角形装饰。

.tooltip {
position: relative;
background: #333;
color: white;
padding: 10px;
}
.tooltip::after {
content: '';
position: absolute;
top: 100%;
left: 50%;
margin-left: -10px;
border-width: 10px;
border-style: solid;
border-color: #333 transparent transparent transparent;
}
控制三角形的大小
调整边框的宽度可以改变三角形的大小。边框宽度越大,三角形尺寸越大。
.large-triangle {
width: 0;
height: 0;
border-left: 100px solid transparent;
border-right: 100px solid transparent;
border-bottom: 200px solid orange;
}
创建带边框的三角形
通过叠加两个不同大小的三角形,可以实现带边框的效果。
.bordered-triangle {
position: relative;
width: 0;
height: 0;
border-left: 52px solid transparent;
border-right: 52px solid transparent;
border-bottom: 104px solid #ccc;
}
.bordered-triangle::after {
content: '';
position: absolute;
left: -50px;
top: 4px;
width: 0;
height: 0;
border-left: 50px solid transparent;
border-right: 50px solid transparent;
border-bottom: 100px solid #f00;
}






