<div id="div1"></div>
<div id="div2"></div>
<div id="div3"></div>
<div id="div4"></div>
<div id="div5"></div>
<div id="div6"></div>
#div1 { width: 0; height:0; border-right: 40px solid transparent; border-left: 40px solid transparent; border-bottom:80px solid red }
ps : transparent为设置透明
为了探究css画三角形的原理,先来实验一下,试试单边
#div1 { width: 0; height:0; border-top: 40px solid ; } #div2 { width: 0; height:0; border-right: 40px solid ; } #div3 { width: 0; height:0; border-bottom: 40px solid ; } #div4 { width: 0; height:0; border-left: 40px solid ; }
发现没有显示,再来试试两条边
#div1 { width: 0; height:0; border-top: 40px solid ; border-right: 40px solid red; } #div2 { width: 0; height:0; border-top: 40px solid ; border-bottom: 40px solid red; } #div3 { width: 0; height:0; border-top: 40px solid ; border-left: 40px solid red; } #div4 { width: 0; height:0; border-right: 40px solid ; border-bottom: 40px solid red; } #div5 { width: 0; height:0; border-right: 40px solid ; border-left: 40px solid red; } #div6 { width: 0; height:0; border-bottom: 40px solid ; border-left: 40px solid red; }
发现只有相邻边才会显示,相对边不显示,然后试试三边/四边发现都能显示
为什么设置宽高为0时就会呈三角形?如果设置宽高呢?
#div1 { width: 20px; height:20px; border-top: 40px solid ; border-right: 40px solid red; border-bottom: 40px solid green; border-left: 40px solid yellow; }
为了更清晰的地对比,再来看一看
#div1 { width: 20px; height:20px; border-top: 40px solid ; border-right: 40px solid red; border-bottom: 40px solid green; border-left: 40px solid yellow; } #div2 { width: 0; height:0; border-top: 40px solid ; border-right: 40px solid red; border-bottom: 40px solid green; border-left: 40px solid yellow; } #div3 { width: 0; height:0; border-top: 40px solid ; border-left: 40px solid red; border-bottom: 40px solid green; } #div4 { width: 0; height:0; border-top: 40px solid ; border-left: 40px solid red; }
从下往上解读:
1、当宽高为0时,只有两条边,即可以看作朝指定方向缩进、对应宽高的矩形(div4,左上缩进,宽(border-left)40px,,高(border-top)40px),
2、当宽高为0时,只有三条边,即可看做全部组合的、朝指定方向缩进、对应宽高的矩形
( div3,[左上缩进,宽(border-left)40px,,高(border-top)40px],[左下缩进,宽(border-left)40px,,高(border-bottom)40px],[上下缩进,对应边不显示] ),靠左拼接
3、当宽高为0时,有四条边,即可看做全部组合的、朝指定方向缩进、对应宽高的矩形
( div2,{ [左上缩进,不再重复......],[右上缩进,......] 靠上拼接},{ [右上缩进,......],[右下缩进,......] 靠右拼接},{ [右下缩进,......],[左下缩进,......] 靠下拼接},{ [左下缩进,不再重复......],[左上缩进,......] 靠左拼接} )
4、当宽高不为0时,根据盒子模型,border在外围,会被元素撑开