CSS3 before、after偽元素實現氣泡框
阿新 • • 發佈:2019-01-05
氣泡框的原理其實也就是普通邊框+三角形,CSS實現三角形也是利用了border屬性
1、三角形是實心的
html程式碼:
<div class="wrap"></div>
css程式碼:
.wrap{
position: relative;
width: 600px;
height: 400px;
border: 10px solid #3377aa;
border-radius: 20px;
}
.wrap ::before{
position: absolute;
content: '';
width: 0;
height: 0;
border-width: 40px 20px; /*上下、左右的border值*/
border-style: solid;
border-color: #3377aa transparent transparent;/*只設置上面border的顏色,左右和下面都設定為透明,會出現一個倒三角*/
bottom : -80px; /*以下給三角形定位,使其處於底部居中處*/
left: 50%;
margin-left: -20px;
}
效果圖:
2、如果需要三角形是空心的,效果圖如下,需要同時使用before和after
css程式碼如下:
.wrap::before{
position: absolute;
content: '';
width: 0;
height: 0;
border-width : 40px 20px;
border-style: solid;
border-color: #3377aa transparent transparent;
bottom: -80px;
left: 50%;
margin-left: -20px;
}
.wrap::after{
position: absolute;
content: '';
width: 0;
height: 0;
border-width: 40px 20px;
border-style: solid;
border-color: #fff transparent transparent;/*白色的倒三角*/
bottom: -60px; /*位置和往上一些*/
left: 50%;
margin-left: -20px;
}
簡寫的話是這樣:
.wrap::before,
.wrap::after{
position: absolute;
content: '';
width: 0;
height: 0;
border-width: 40px 20px;
border-style: solid;
border-color: #3377aa transparent transparent;
bottom: -80px;
left: 50%;
margin-left: -20px;
}
.wrap::after{
border-color: #fff transparent transparent;
bottom: -60px;
}
原理就是將兩個三角形疊加,下面的三角形border顏色和外面的框一致,上面的border顏色設定為白色,為了能更好看清,我將body顏色設為#ccc,如下: