css當中:before和:after選擇器

weixin_33860722發表於2017-03-05

:before和:after作為偽元素,用於在某個元素之前或之後插入某些內容
舉個例子

<style>
p:before{
content: "H"
}
p:after{
content: "d"
}
</style>
<p>ello Worl</p>

則輸出的顯示仍然是"hello world"

審查元素可以發現

<p>
::before
"ello Worl"
::after
</p>

1.結合border寫個對話方塊的樣式

怎樣用border畫三角形

<style>
.triangle{
width: 0;
height: 0;
border-left:50px solid red;
border-bottom:50px solid blue;
border-top:50px solid black;
border-right:50px solid purple
}
</style>
<div class="triangle"></div>

此時會顯示一個正方形,中間含有四個三角形
應該要進行修改

4958474-55fe25d889cd678a.png
2017-03-05 18-11-02螢幕截圖.png

.triangle{
width: 0;
height: 0;
border:50px transparent solid; /這裡我們將元素的邊框寬度設定為50px,transparent表示邊框顏色是透明的,solid表示邊框是實線的/
border-top-color: black; /這裡我們僅將上邊框的顏色設定為黑色,眾所周知,css後面的樣式程式碼會覆蓋之前的相同的樣式程式碼,至於其他三邊的還是透明色/
/border-bottom-color: black; //這裡設定底部邊框色為黑色
border-left-color: black; //這裡設定左邊邊框色為黑色
border-right-color:black //這裡設定右邊邊框色為黑色
/
}

效果:上部的樣式覆蓋了透明,其餘三部仍為透明

4958474-0beb899196109ddb.png
2017-03-05 18-26-23螢幕截圖.png

然後加上before:

.test-div{
position: relative; /日常相對定位/
width:150px;
height:36px;
border-radius:5px;
border:black 1px solid;
background: rgba(245,245,245,1)
}
.test-div:before{
content: ""; /:before和:after必帶技能,重要性為滿5顆星/
display: block;
position: absolute; /日常絕對定位/
top:8px;
width: 0;
height: 0;
border:6px transparent solid;
left:-12px;
border-right-color: rgba(0,245,245,1);
}

效果:三角形圖示沒有邊框

4958474-105286b700ed08bc.png
對話方塊0.png

使用了after之後:

.test-div{
position: relative; /日常相對定位/
width:150px;
height: 36px;
border:black 1px solid;
border-radius:5px;
background: rgba(245,245,245,1)
}
.test-div:before,.test-div:after{
content: ""; /:before和:after必帶技能,重要性為滿5顆星/
display: block;
position: absolute; /日常絕對定位/
top:8px;
width: 0;
height: 0;
border:6px transparent solid;
}
.test-div:before{
left:-11px;
border-right-color: rgba(245,245,245,1);
z-index:1
}
.test-div:after{
left:-12px;
border-right-color: rgba(0,0,0,1);
z-index: 0
}

實質上是利用了前後兩次的一個位移差,使得只顯示出一個邊線

4958474-99af2b233077a50e.png
對話方塊.png

2.作為內容的半透明背景層

body{
background: url(img/1.jpg) no-repeat left top /這裡本獸加了個圖片背景,用以區分背景的半透明及內容的完全不透明/
}
.test-div{
position: relative; /日常相對定位(重要,下面內容也會介紹)/
width:300px;
height: 120px;
padding: 20px 10px;
font-weight: bold;
}
.test-div:before{
position: absolute; /日常絕對定位(重要,下面內容也會略帶介紹)/
content: ""; /:before和:after必帶技能,重要性為滿5顆星/
top:0;
left: 0;
width: 100%; /和內容一樣的寬度/
height: 100%; /和內容一樣的高度/
background: rgba(255,255,255,.5); /給定背景白色,透明度50%/
z-index:-1

4958474-364c72618ee6979f.png
透明.png

相關文章