- 基本語法
平常僅僅需要將這兩個(gè)偽元素用于添加一些自定義字符時(shí)嗅骄,只需使用偽類使用的單冒號(hào)寫法譬猫,以保證瀏覽器的兼容性怨规。
不 過,在 CSS3 中為了區(qū)別偽元素和偽類為偽元素使用了雙冒號(hào)咆疗,因此如果使用了 display 或者 width 等屬性時(shí)使得顯示脫離了原本元素后,建議按照標(biāo)準(zhǔn)雙寫母债。
屬性 content 午磁,用于在 CSS 渲染中向元素邏輯上的頭部或尾部添加內(nèi)容尝抖。
注意這些添加不會(huì)改變文檔內(nèi)容,不會(huì)出現(xiàn)在 DOM 中迅皇,不可復(fù)制昧辽,僅僅是在 CSS 渲染層加入。在Web頁面的HTML源代碼里登颓,你實(shí)際上找不到它們搅荞,但從視覺上,你卻能看到它們的存在框咙,所以我們用這個(gè)“偽”字就是表示它們假元素咕痛。
2.基本用法:
給元素前后添加內(nèi)容,如給一個(gè)blockquote元素之前和之后加入引號(hào)
<style>
blockquote:before {
content: open-quote;
}
blockquote:after {
content: close-quote;
}
</style>
<blockquote>
這是一個(gè)段落啊~
</blockquote>
效果: “這是一個(gè)段落啊~”
:before和:after雖然是偽元素喇嘱,但它們所有用法和行為表現(xiàn)和真正的元素幾乎完全一樣茉贡;
我們可以對(duì)它們進(jìn)行任何的CSS樣式設(shè)置,例如婉称,改變它們的前景顏色块仆,增加背景色/圖,調(diào)整字體大小王暗,調(diào)整對(duì)齊方式等等悔据。
<style>
blockquote:before {
content: open-quote;
font-size: 24pt;
text-align: center;
line-height: 42px;
color: #fff;
background: #ddd;
float: left;
position: relative;
top: 0px;
}
blockquote:after {
content: close-quote;
font-size: 24pt;
text-align: center;
line-height: 42px;
color: #fff;
background: #ddd;
float: right;
position: relative;
bottom: 10px;
right: 1300px;
}
</style>
- 特效妙用
鼠標(biāo)移上鏈接,出現(xiàn)方括號(hào):
<style>
a {
position: relative;
display: inline-block;
outline: none;
text-decoration: none;
color: #000;
font-size: 32px;
padding: 5px 10px;
margin-left: 200px;
cursor: pointer;
}
a:hover::before, a:hover::after { position: absolute; }
a:hover::before { content: "\5B"; left: -20px;color: #B20E00; }
a:hover::after { content: "\5D"; right: -20px;color: #B20E00; }
</style>
4.對(duì)文字進(jìn)行美化
Html代碼:
<body>
<span data-text='COOL'>COOL</span>
</body>
css代碼:
<style>
{
padding: 0;
margin: 0
}
span{
position: relative;
font-size: 12rem;
color: #0099CC
}
span::before{
position: absolute;
font-size: 12rem;
color: #333;
content: attr(data-text);
white-space:nowrap;
width: 50%;
/此為左右型美化俗壹,若要改成上下型科汗,則將此行變?yōu)閔eight:50%;*/
display: inline-block;
overflow: hidden
}
</style>