方法一:border
先看看四邊 border 顏色不同且不透明時的效果:
.rect1 { width: 0px; height: 0px; margin: auto; border: 20px solid red; border-left-color: blue; border-right-color: yellow; border-top-color: purple; } .rect2 { width: 0px; height: 0px; margin: auto; border-top: 20px solid red; border-left: 10px solid blue; border-right: 15px solid yellow; border-bottom: 25px solid purple; } .rect3 { width: 10px; height: 0px; margin: auto; border: 20px solid red; border-left-color: blue; border-right-color: yellow; border-top-color: purple; } .rect4 { width: 10px; height: 10px; margin: auto; border: 20px solid red; border-left-color: blue; border-right-color: yellow; border-top-color: purple; } <!--html--> <div class='rect1'></div> <div class='rect2'></div> <div class='rect3'></div> <div class='rect4'></div>
以上 rect1、rect3、rect4 個 div 的區別在於 width 和 height 的大小,而 rect2 的 4 邊 border-width 值各不相同。
哈哈,三角形和梯形都出來啦。利用 border 屬性,一個或多個元素可以組合出不同的圖形。
除了 border 屬性,還可以借助偽元素來實現三角形。
方法二:偽元素
看代碼:
<!--css--> .pseudo-ele { width: 20px; height: 20px; background: transparent; overflow: hidden; } .pseudo-ele:after { display: block; width: 150%; height: 150%; content: ''; background: red; transform: rotateZ(45deg) translateX(10px); } <!--html--> <div class='pseudo-ele'></div>
父元素需要設置 overflow: hidden,將偽元素超出范圍的部分遮擋掉。
方法三:background
<!--css--> .linear { width: 30px; height: 30px; -webkit-background: linear-gradient(45deg, transparent 50%, red 50%, red 100%) background: linear-gradient(45deg, transparent 50%, red 50%, red 100%) } <!--html--> <div class='linear'></div>
通過漸變的方式,實現三角形,但是需要注意兼容性的問題。
還有最原始的方法,就是用三角形背景圖啦。
參考:
《css揭秘》