用css畫三角形(提示框三角形)
阿新 • • 發佈:2019-01-24
三角形使用情形
- 經常用於提示框,下拉選單等(csdn也很多用到,最後一圖),看圖:
- 由於在網頁中經常要用到,所以特地研究
- 圖片實現(感覺low)、svg實現(小題大作了),所以最後還是css畫比較不錯,相容性也不錯
三角形畫法
- html結構
<div class="triangle">
</div> - 三角形畫法
- 用border畫出,當width、height均為100px時
.triangle {
width: 100px;
height: 100px;
border-left: 10px solid #7d7b7b ;
border-top: 10px solid #5851c3;
border-right: 10px solid #21a4d6;
border-bottom: 10px solid #4ed621;
box-sizing: border-box;
}
–>結果:
改變{width:0; height:0}
–>
–>再去掉border-top
—>
–>可以看見上面的一半已經沒有了
–>設定左右兩邊border-color:transparent;
–>
–>就得到了想要的三角形了,這是向上的,想要哪邊就畫哪邊的border,並且讓它相鄰兩邊的border-color:transparent
–>程式碼
.triangle {
width: 0;
height: 0;
border-left: 10px solid transparent;
/*border-top: 10px solid #5851c3;*/
border-right: 10px solid transparent;
border-bottom: 10px solid #4ed621;
box-sizing: border-box;
}
畫提示框三角形(有邊緣的)
如圖:
- 原理:先畫一個三角形,再畫白色三角形的,調整幾畫素位置,覆蓋掉一邊
–>
- 程式碼
.triangle {
position: relative;
width: 100px;
height: 50px;
border: 2px solid #4ed621;
border-radius: 5px;
}
.triangle:before {
position: absolute;
content: "";
top: -10px;
left: 25px;
border-left: 10px solid transparent;
border-right: 10px solid transparent;
border-bottom: 10px solid #4ed621;
}
/* 白色覆蓋*/
.triangle:after {
position: absolute;
content: "";
/*減少兩畫素*/
top: -8px;
left: 25px;
border-left: 10px solid transparent;
border-right: 10px solid transparent;
border-bottom: 10px solid #fff;
}
<div class="triangle"></div>
結果:
–> –>
- 至此,三角形畫完,只用到了css2的屬性,相容性一覽無餘
- 推薦一款優秀的線上畫圖工具,很不錯(不是廣告啊!)