css 實現三角形
盒模型中的div默認是一個矩形。那麼我們怎麼實現三角形呢。
使用字符中的符號。這個跟字體相關,在布局上基本沒什麼用。
矩形沿着一個角用斜線切一刀就可以得到三角形
一、怎麼實現切一刀呢?
1、寬高為0的矩形。設置邊框。可以將矩形分為四個三角形。
#demo1 { width: 0; height:0; border-top: 100px solid red; border-bottom: 50px solid green; border-left: 50px solid blue; border-right: 50px solid grey; }
2、使用無過渡線性漸變的方式
#demo2 { width: 200px; height: 100px; background: linear-gradient(45deg, red, red 70.72px, green 70.72px, green 200px); }
3、使用角向漸變
#demo3 { width: 200px; height: 100px; background: conic-gradient(from 90deg at 0 0, red 0, red 10deg, green 10deg); }
4、使用旋轉出父元素,超出隱藏的方式。
#demo4 { width: 300px; height: 100px; position: relative; overflow: hidden; } #demo4::before { content: ""; position: absolute; top: 0; left: 0; right: 0; bottom: 0; background: red; transform-origin: left bottom; transform: rotate(65deg); }
5、css裁剪屬性
#demo5 { width: 100px; height: 100px; background: red; clip-path: polygon(0 0, 50px 0, 0 100px, 0 0); }
二、怎麼實現角度呢?
使用 rotate
,實現不同角度
#demo7 { width: 0; height: 0; border-top: 100px solid red; border-bottom: 50px solid green; border-left: 50px solid blue; border-right: 50px solid grey; transform: rotate(45deg); }
三、移除不必要的部分
例1-例3中把不要的部分顏色設置為transparent就可以了。
#demo8 { width: 0; height: 0; border-top: 100px solid red; border-bottom: 50px solid transparent; border-left: 50px solid transparent; border-right: 50px solid transparent; transform: rotate(45deg); }
四、調整佔位
如上的方式實現三角形後,在流中,會額外佔用一部分位置。需要調整一下,這裡根據具體需求來,例1中使用margin-bottom將不需要的border-bottom佔用的50px拉回去。
下面的例子還存在着旋轉導致的位置偏移。所以拉回去50px的效果依然不理想。這裡需要根據實際的需求來調整了。沒有一個完美的方案。
#demo9 { width: 0; height: 0; border-top: 100px solid red; border-bottom: 50px solid transparent; margin-bottom:-50px; border-left: 50px solid transparent; border-right: 50px solid transparent; transform: rotate(45deg); } #demo10 { width: 100px; height: 100px; border:1px solid green; }
五、兼容性
上面的部分方法。不能在IE11之前正常運行。