为什么这个 CSS 片段可以画出一个三角形?

Why can this CSS snippet draw a triangle?

我看到下面的代码,没有任何评论..

.triangle {
    border-color: transparent;
    border-bottom-color: green;
    border-style: solid;
    border-width:  300px;
    border-top-width:0;
    height: 0;
    width: 0
}
<div class="triangle"></div>

结果是一个绿色三角形。有人知道它为什么有效吗?

边界的角以 45 度角相交。

所以只显示一个边框将显示一侧与另一侧相接的锥形边缘。

通过使 3 个边框不可见或与背景颜色相同,我们得到三角形的错觉。

.bdr1{
  height:100px;
  width:100px;
  display:block;
  border:25px solid;
  border-color:red blue green black;
 }
.bdr2{
  height:0;
  width:0;
  display:block;
  border:100px solid;
  border-color:red blue green black;
 }
.bdr3{
  height:0;
  width:0;
  display:block;
  border:100px solid;
  border-color:red white white white;
 }
<div class="bdr1"></div><br/>
<div class="bdr2"></div><br/>
<div class="bdr3"></div>


塑造未来

这项技术创造了一种极好的方法,可以仅使用 css。

来创建更精细的形状

星级

.Star{ 
  width: 0; 
  height: 0; 
  border-left: 50px solid transparent; 
  border-right: 50px solid transparent; 
  border-bottom: 100px solid red; 
  position: relative; 
} 
.Star:after { 
  width: 0; height: 0; 
  border-left: 50px solid transparent; 
  border-right: 50px solid transparent; 
  border-top: 100px solid red;
  position: absolute; content: ""; 
  top: 30px; 
  left: -50px; 
}
<div class="Star"></div>


雪佛龙

.Chevron{
    position:relative;
    display:block;
    height:50px;/*height should be double border*/
}
.Chevron:before,
.Chevron:after{
    position:absolute;
    display:block;
    content:"";
    border:25px solid transparent;/*adjust size*/
}
/*Change four 'top' values below to rotate (top/right/bottom/left)*/
.Chevron:before{
    top:0;
    border-top-color:#b00;/*Chevron Color*/
}
.Chevron:after{
    top:-10px;/*adjust thickness*/
    border-top-color:#fff;/*Match background colour*/
}
<i class="Chevron"></i>

这是因为您看到的只是bottom-border-color。左右边框透明,上边框完全没有宽度(border-top-width:0;).

元素边框相交的角度根据两个边框的宽度计算得出。因此,如果边框宽度相同,则角度为 45 度。不相等的边框宽度会产生其他角度。

因为 .triangle 元素没有宽度或高度,所以这些角度会聚在一个点上。下面的代码将有助于演示这个概念:

    .borders {
        border-bottom-color: green;
        border-left-color: red;
        border-right-color: blue;
        border-top-color: pink;
        border-style: solid;
        border-width:  50px;
        height: 50px;
        width: 50px;
    }

    .triangles {
        border-bottom-color: green;
        border-left-color: red;
        border-right-color: blue;
        border-top-color: pink;
        border-style: solid;
        border-width:  50px;
        height: 0;
        width: 0;
    }

    .triangle {
        border-color: transparent;
        border-bottom-color: green;
        border-style: solid;
        border-width:  50px;
        height: 0;
        width: 0;
    }
<div class="borders"></div>
<hr>
<div class="triangles"></div>
<hr>
<div class="triangle"></div>