border實現三角形的原理


前言:網上最普遍的實現三角形的方法,就是通過控制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;
}

image

觀察上圖可以發現,border表現為梯形。當減小box的寬高時,會發生如下變化:

image

從上圖很容易看出,當box寬度降低到很小,也就是border的梯形的上邊降到很小。所以想一想,當這一值降到0時,border就變成了三角形。如下圖:

image

所以我們就可以通過將元素寬高設置為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;
}

image

#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;
}

 

image

#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;
}

image

#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;
}

image

 

就不一一列舉了,只要明白每個方向的border都是一個三角形,就能通過調整border的大小和顏色/透明,獲得各種三角形和梯形了。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM