上次講了一些基本的 CSS 形狀,實(shí)際的網(wǎng)頁(yè)當(dāng)中當(dāng)然不只是這些普通的三角形,還有很多復(fù)雜一點(diǎn)的圖形,比如搜索框中的放大鏡等等,這時(shí)為了不添加額外元素就要用到偽元素 ::before 和 ::after。
什么是偽元素##
簡(jiǎn)而言之,偽元素會(huì)在內(nèi)容元素的前后插入額外的元素,但這些元素實(shí)際上并不在文檔中生成,它們?cè)谕獠靠梢?jiàn)但是你將不會(huì)在源代碼中找到它們,因此,實(shí)際上它們是“虛假”的元素。
使用偽元素繪制圖標(biāo)##
讓我們先來(lái)繪制一個(gè)放大鏡的圖標(biāo),最后的結(jié)果如下圖所示:

先繪制一個(gè)圓圈,很簡(jiǎn)單:
#magnifier {
position: relative;
width: 50px;
height: 50px;
border: 5px solid red;
border-radius: 999em;
}
那放大鏡的手柄怎么辦呢,在不添加元素的情況下用偽元素就很容易做到:
#magnifier::before {
content: "";
position: absolute;
left: 45px;
top: 45px;
width: 40px;
height: 10px;
background-color: red;
-webkit-transform-origin: 5px 5px;
transform-origin: 5px 5px;
-webkit-transform: rotate(45deg);
transform: rotate(45deg);
}
再來(lái)繪制一個(gè)復(fù)雜一點(diǎn)的,圖片圖標(biāo):

先繪制一個(gè)外框:
#image {
position: relative;
width: 100px;
height: 80px;
border: 5px solid red;
overflow: hidden;
}
再用 ::before 偽元素繪制太陽(yáng):
#image::before {
content: "";
position: absolute;
left: 10px;
top: 10px;
width: 20px;
height: 20px;
border-radius: 999em;
background-color: red;
}
那剩下的兩座山怎么辦呢,只剩下一個(gè) ::after 偽元素了,可以用 box-shadow 加旋轉(zhuǎn)來(lái)解決:
#image::after {
content: "";
position: absolute;
left: 0px;
top: 50px;
width: 60px;
height: 60px;
background-color: red;
box-shadow: 45px 25px 0px 0px red;
-webkit-transform: rotate(-45deg);
transform: rotate(-45deg);
}
這次就先說(shuō)到這里,下次再討論更更更復(fù)雜的圖形。