插件窝 干货文章 ​CSS如何写出三角形

​CSS如何写出三角形

transparent border 三角形 solid 611    来源:    2025-04-25

使用CSS创建三角形

在CSS中创建三角形是一种常见的技巧,通常用于创建箭头、工具提示等UI元素。以下是几种创建CSS三角形的方法:

方法1:使用边框(border)技巧

这是最常用的方法,通过设置元素的宽高为0,然后利用边框相交处的斜边效果来创建三角形。

.triangle {
  width: 0;
  height: 0;
  border-left: 50px solid transparent;
  border-right: 50px solid transparent;
  border-bottom: 100px solid #f00;
}

不同方向的三角形

/* 向上三角形 */
.triangle-up {
  width: 0;
  height: 0;
  border-left: 50px solid transparent;
  border-right: 50px solid transparent;
  border-bottom: 100px solid #f00;
}

/* 向下三角形 */
.triangle-down {
  width: 0;
  height: 0;
  border-left: 50px solid transparent;
  border-right: 50px solid transparent;
  border-top: 100px solid #f00;
}

/* 向左三角形 */
.triangle-left {
  width: 0;
  height: 0;
  border-top: 50px solid transparent;
  border-right: 100px solid #f00;
  border-bottom: 50px solid transparent;
}

/* 向右三角形 */
.triangle-right {
  width: 0;
  height: 0;
  border-top: 50px solid transparent;
  border-left: 100px solid #f00;
  border-bottom: 50px solid transparent;
}

方法2:使用clip-path

CSS3的clip-path属性提供了更灵活的裁剪方式:

.triangle-clip {
  width: 100px;
  height: 100px;
  background-color: #f00;
  clip-path: polygon(50% 0%, 0% 100%, 100% 100%);
}

不同方向的clip-path三角形

/* 向上 */
clip-path: polygon(50% 0%, 0% 100%, 100% 100%);

/* 向下 */
clip-path: polygon(0% 0%, 100% 0%, 50% 100%);

/* 向左 */
clip-path: polygon(100% 0%, 100% 100%, 0% 50%);

/* 向右 */
clip-path: polygon(0% 0%, 0% 100%, 100% 50%);

方法3:使用transform旋转正方形

.triangle-transform {
  width: 100px;
  height: 100px;
  background-color: #f00;
  transform: rotate(45deg);
  position: relative;
  overflow: hidden;
}

.triangle-transform::before {
  content: '';
  position: absolute;
  width: 141%; /* 100% * √2 ≈ 141% */
  height: 141%;
  background-color: white;
  transform: rotate(45deg) translate(-71%, 0);
}

方法4:使用linear-gradient背景

.triangle-gradient {
  width: 100px;
  height: 100px;
  background: linear-gradient(to bottom right, #f00 0%, #f00 50%, transparent 50%, transparent 100%);
}

注意事项

  1. 边框方法是最兼容的,支持所有现代浏览器和IE8+
  2. clip-path方法更灵活但兼容性稍差(不支持IE)
  3. 对于响应式设计,可以使用百分比值而不是固定像素值
  4. 要创建等腰直角三角形,需要确保两边长度相同

选择哪种方法取决于你的具体需求和浏览器兼容性要求。