CSS語法 - 偽元素
偽元素
使用偽元素能簡化頁面上 HTML 標籤,讓 HTML 的維護更加輕鬆。
在 W3C 的定義裡總共有五個偽元素(其他仍在測試階段),分別是 ::before、::after、::first-line、::first-letter 和 ::selection。
::before 插入在一個元素之前,以 display:inline-block 的屬性存在。
:: after 插入在一個元素之後,以 display:inline-block 的屬性存在。
::first-line 將文本的第一行添加樣式,不能作用於 display:inline 的元素。
::first-letter 將文本的第一個字母添加樣式。
::selection 選取段落文字的樣式屬性。
content 屬性
content 屬性與 ::before 和 ::after 一起使用在文檔中生成內容,使用 ::before 和 ::after 一定要有 content 否則不會發生作用。
content 的值:
- normal | none (預設)
- string 會在之前或之後加入字串,可以針對字串作樣式的變換。
1
2
3
4
5
6
7
8
9div::before {
content: '<';
color: blue;
}
div::after {
content: '>';
color: red;
} - url 插入圖片、聲音或影像。
- attr(屬性) 插入指定屬性的值。
1
2
3
4a::before {
content: attr(href);
color: blue;
} - open-quote | close-quote 給予開始、結束的引號。
1
2
3
4
5
6
7
8
9
10
11
12
13p:before {
content: open-quote;
}
p:after {
content: close-quote;
}
p:before,
p:after {
font-size: 3em;
color: gray;
}- no-open-quote | no-close-quote 取消開始、結束的引號。
- 使用空白可以相加 content 的內容。
1
2
3
4a::before {
content: ''attr(href)' <';
color: blue;
}
搭配 quotes 屬性
在元素上設定自定義的括號。
quotes 支援巢狀的結構,前後括號使用空白區隔,兩組為一個單位,前後可以不同符號。
1 | p { |
參考資料 :
MDN