Skip to content

CSS 三角形

使用 border 实现三角形

一个元素的可以单独设置四边框的样式,每边以对角线(45 度)的方式相互连接。

html
<div class="wrap">
  <div class="arrow-box"></div>
  <div class="arrow-box no-size"></div>
</div>
css
.wrap {
  display: grid;
  grid-auto-flow: column;
  gap: 16px;
}
.arrow-box { 
  box-sizing: content-box;
  width: 30px; 
  height: 30px; 
  border-top: 20px solid #3AA1F5; 
  border-right: 20px solid #9EA2FE; 
  border-bottom: 20px solid #EE6F9A; 
  border-left: 20px solid #F9A677; 
} 
.arrow-box.no-size { 
  width: 0; 
  height: 0; 
} 

结果


所以绘制一个三角的符号可以隐藏相邻的2边和对角的边

html
<div class="wrap">
  <div class="arrow-up"></div> 
  <div class="arrow-right"></div> 
  <div class="arrow-down"></div> 
  <div class="arrow-left"></div> 
</div>
css
.wrap {
  display: grid;
  grid-auto-flow: column;
  gap: 16px;
}
.arrow-up { 
  width: 0; 
  height: 0; 
  border-left: 20px solid transparent; 
  border-right: 20px solid transparent; 
  border-bottom: 20px solid #3AA1F5; 
} 
.arrow-right { 
  width: 0; 
  height: 0; 
  border-top: 20px solid transparent; 
  border-bottom: 20px solid transparent; 
  border-left: 20px solid #9EA2FE; 
}
.arrow-down { 
  width: 0; 
  height: 0; 
  border-left: 20px solid transparent; 
  border-right: 20px solid transparent; 
  border-top: 20px solid #EE6F9A; 
} 
.arrow-left { 
  width: 0; 
  height: 0; 
  border-top: 20px solid transparent; 
  border-bottom: 20px solid transparent; 
  border-right: 20px solid #F9A677; 
} 

结果


使用 clip-path 实现三角形

clip-path CSS 属性使用裁剪方式创建元素的可显示区域。区域内的部分显示,区域外的隐藏。

其中 polygon() 可以通过提供一个或多个坐标对(每一个坐标代表形状的一个顶点)来绘制多边形,所以可以提供 3 个坐标点绘制三角形。

html
<div class="wrap">
  <div class="arrow-up"></div> 
  <div class="arrow-right"></div> 
  <div class="arrow-down"></div> 
  <div class="arrow-left"></div> 
</div>
css
.wrap {
  display: grid;
  grid-auto-flow: column;
  gap: 16px;
}
.arrow-up { 
  width: 40px; 
  height: 20px; 
  background-color: #3AA1F5; 
  clip-path: polygon(50% 0, 0 100%, 100% 100%); 
} 
.arrow-right { 
  width: 20px; 
  height: 40px; 
  background-color: #9EA2FE; 
  clip-path: polygon(0 0, 0 100%, 100% 50%);  
} 
.arrow-down { 
  width: 40px; 
  height: 20px; 
  background-color: #EE6F9A; 
  clip-path: polygon(100% 0, 0 0, 50% 100%);  
} 
.arrow-left { 
  width: 20px; 
  height: 40px; 
  background-color: #F9A677; 
  clip-path: polygon(100% 100%, 100% 0, 0 50%);  
} 

结果