css3制作三角形
使用 CSS3 制作三角形的方法
边框法(Border Method)
通过设置元素的 width 和 height 为 0,利用边框的透明属性生成三角形。
将三个边框设为透明,第四个边框设置颜色,形成三角形效果。
代码示例:
.triangle {
width: 0;
height: 0;
border-left: 50px solid transparent;
border-right: 50px solid transparent;
border-bottom: 100px solid #ff0000;
}
border-bottom设置颜色,生成向上的三角形。- 调整
border-left、border-right、border-top或border-bottom的颜色和宽度可改变方向。
变换法(Transform Method)
通过旋转正方形元素并隐藏溢出部分生成三角形。
代码示例:

.triangle {
width: 100px;
height: 100px;
background-color: #ff0000;
transform: rotate(45deg);
overflow: hidden;
position: relative;
}
- 需要配合
overflow: hidden裁剪多余部分。 - 适用于复杂场景,但实现稍繁琐。
伪元素法(Pseudo-element Method)
结合伪元素和边框法,避免额外 HTML 元素。
代码示例:

.element::after {
content: '';
display: block;
width: 0;
height: 0;
border-left: 30px solid transparent;
border-right: 30px solid transparent;
border-top: 50px solid #00ff00;
}
- 常用于工具提示或下拉菜单的箭头。
线性渐变法(Linear Gradient Method)
使用 linear-gradient 背景生成三角形。
代码示例:
.triangle {
width: 100px;
height: 100px;
background: linear-gradient(to bottom right, #0000ff 50%, transparent 50%);
}
- 适合需要渐变效果的三角形。
- 兼容性稍弱,需前缀支持。
注意事项
- 边框法是最常用且兼容性最好的方案。
- 调整边框宽度比例可改变三角形的形状和大小。
- 结合
clip-path(现代浏览器)可实现更复杂的多边形。
示例:调整方向的边框法
/* 向左的三角形 */
.left-triangle {
border-top: 50px solid transparent;
border-bottom: 50px solid transparent;
border-right: 100px solid #ff00ff;
}




