今天學到了怎么做一個小三角形,進而結合其他屬性把類似微信對話框的圖形做出來了。
先做出如下形狀:
.arrow { width: 30px; height:30px; border-width:20px; border-style:solid; border-color:#e66161 #f3bb5b #94e24f #85bfda; }
將width,height重置成0,就有了:
調整顏色,有了下圖:
以下代碼可以實現上圖:
<style> .test { width: 0; height: 0; border: 10px solid transparent;
border-top: 10px solid black; // border-top控制三角形尖朝下,可改變
} </style> <div class="test"></div>
//注:IE6下把邊框設置成 transparent 時會出現黑影,並不會透明,把 border-style 設置成 dashed 可以解決。
然后我們再做一個沒有突出三角形的對話框出來:
<style> .test-div{ position: relative; width:150px; height: 36px; border:1px solid black; border-radius:5px; background: rgba(245,245,24,1) } </style> <div class="test-div"></div>
下一步,我們可以把剛才做好的那個三角形放在對話框旁邊(使用絕對定位)讓它突出來,利用偽類:before實現:
.test-div{
position: relative; /*日常相對定位*/
width:150px;
height: 36px;
border:1px solid black;
border-radius:5px;
background: rgba(245,245,24,1);
}
.test-div:before {
content: "";
display: block;
position: absolute;
width:0;
height: 0;
border: 6px solid transparent;
border-right-color: rgba(245,245,24,1);
left: -12px;
top: 8px;
}
可以看到,左側有一個凸起的三角尖了。三角尖的位置由絕對定位決定。
但問題是這個三角形沒有邊框,怎么給它加上呢?可以再用:after偽類疊加一個大小相同的三角尖,但位置稍稍錯開,再隱藏:before形成的三角尖,效果就像給原來的三角尖加了邊框一樣。
.test-div:before,.test-div:after { content: ""; display: block; position: absolute; width:0; height: 0; border: 6px solid transparent; border-right-color: rgba(245,245,24,1); left: -11px; top: 8px; z-index:1; } .test-div:after { left: -12px; border-right-color: black; z-index:0; }
z-index控制層疊元素的疊加順序,它的值越大,那一層就越在上面。這個例子中我們讓:before的三角尖在上面,隱藏了:after三角尖的一部分,只留出了:after邊框,效果就像:before的三角尖有邊框一樣。效果如下: