轉自:https://www.cnblogs.com/youhong/p/6530575.html
前言:網上最普遍的實現三角形的方法,就是通過控制border來實現,那為什么可以呢?
原理
我們先來看看border的表現形式。
#box{
width:100px;
height:100px;
background:yellow;
border-top: 20px solid red;
border-right:20px solid black;
border-bottom:20px solid green;
border-left:20px solid blue;
}
觀察上圖可以發現,border表現為梯形。當減小box的寬高時,會發生如下變化:
從上圖很容易看出,當box寬度降低到很小,也就是border的梯形的上邊降到很小。所以想一想,當這一值降到0時,border就變成了三角形。如下圖:
所以我們就可以通過將元素寬高設置為0,而通過控制border來得到想要的三角形了。
實現
將不需要方向的border設置為透明(transparent),就可以用來實現三角形了。比如想實現下三角形,就將border-left,border-bottom,border-right設置為transparent即可。
#box{
width:0px;
height:0px;
border-top: 20px solid red;
border-right:20px solid transparent;
border-bottom:20px solid transparent;
border-left:20px solid transparent;
}
#box{
width:0px;
height:0px;
border-top: 20px solid red;
border-right:20px solid transparent;
border-bottom:20px solid transparent;
border-left:20px solid red;
}
#box{
width:0px;
height:0px;
border-top: 60px solid red;
border-right:20px solid transparent;
border-bottom:0px solid transparent;
border-left:20px solid transparent;
}
#box{
width:100px;
height:100px;
border-top: 60px solid red;
border-right:20px solid transparent;
border-bottom:0px solid transparent;
border-left:20px solid transparent;
}







