css怎么制作三角形
使用边框制作三角形
通过设置元素的 border 属性,利用边框交汇处的斜切特性生成三角形。将元素的宽度和高度设为 0,仅通过边框的宽度和颜色控制形状。
.triangle {
width: 0;
height: 0;
border-left: 50px solid transparent;
border-right: 50px solid transparent;
border-bottom: 100px solid red;
}
控制三角形方向
调整边框的显示与隐藏可以改变三角形方向。例如,隐藏左、右、上或下边框,仅保留一个方向的边框。
.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;
}
.triangle-left {
border-top: 50px solid transparent;
border-bottom: 50px solid transparent;
border-right: 100px solid yellow;
}
.triangle-right {
border-top: 50px solid transparent;
border-bottom: 50px solid transparent;
border-left: 100px solid purple;
}
使用伪元素生成三角形
通过 ::before 或 ::after 伪元素生成三角形,避免污染 DOM 结构。适用于需要动态添加三角形的场景。
.element::after {
content: "";
display: block;
width: 0;
height: 0;
border-left: 20px solid transparent;
border-right: 20px solid transparent;
border-top: 40px solid black;
}
使用 clip-path 绘制三角形
通过 clip-path 属性直接裁剪出三角形路径,支持更复杂的形状和动画效果。
.triangle-clip {
width: 100px;
height: 100px;
background-color: orange;
clip-path: polygon(50% 0%, 0% 100%, 100% 100%);
}
结合 transform 旋转三角形
通过 transform 旋转边框生成的三角形,实现斜向或自定义角度的三角形。
.triangle-rotate {
width: 0;
height: 0;
border-left: 50px solid transparent;
border-right: 50px solid transparent;
border-bottom: 100px solid pink;
transform: rotate(45deg);
}
注意事项
- 边框法生成的三角形大小由
border-width决定,调整数值可改变尺寸。 clip-path的兼容性较新,需检查目标浏览器支持情况。- 伪元素法需确保父元素具有非
static的定位(如relative),以便定位三角形。







