CSS偽元素是用來添加一些選擇器的特殊效果。用於:向某個選擇器中的文字的首行。
㈠語法
①偽元素的語法:
selector:pseudo-element {property:value;}
②CSS類也可以使用偽元素:
selector.class:pseudo-element {property:value;}
㈡:first-line 偽元素
⑴"first-line" 偽元素用於向文本的首行設置特殊樣式。
⑵"first-line" 偽元素只能用於塊級元素。
⑶下面的屬性可應用於 "first-line" 偽元素:
- font properties
- color properties
- background properties
- word-spacing
- letter-spacing
- text-decoration
- vertical-align
- text-transform
- line-height
- clear
⑷示例:瀏覽器會根據 "first-line" 偽元素中的樣式對 p 元素的第一行文本進行格式化
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>:first-line</title> <style> p:first-line { color:deeppink; font-variant:small-caps; } </style> </head> <body> <p>你可以使用 "first-line" 偽元素向文本的首行設置特殊樣式。</p> </body> </html>
效果圖:
㈢:first-letter 偽元素
⑴"first-letter" 偽元素用於向文本的首字母設置特殊樣式
⑵"first-letter" 偽元素只能用於塊級元素。
⑶下面的屬性可應用於 "first-letter" 偽元素:
- font properties
- color properties
- background properties
- margin properties
- padding properties
- border properties
- text-decoration
- vertical-align (only if "float" is "none")
- text-transform
- line-height
- float
- clear
⑷示例:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>首字母特殊樣式</title> <style> p:first-letter { color:#ff0000; font-size:xx-large; } </style> </head> <body> <p>用美好的心情去面對接下來會發生的每一件事。</p> </body> </html>
效果圖:
㈣偽元素和CSS類
偽元素可以結合CSS類
示例:使所有 class 為 article 的段落的首字母變為紅色。
p.article:first-letter {color:#ff0000;} <p class="article">文章段落</p>
㈤多個偽元素
示例:段落的第一個字母將顯示為紅色,其字體大小為 xx-large。
第一行中的其余文本將為藍色,並以小型大寫字母顯示。
段落中的其余文本將以默認字體大小和顏色來顯示:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>結合示例</title> <style> p:first-letter { color:deeppink; font-size:xx-large; } p:first-line { color:blue; font-variant:small-caps; } </style> </head> <body> <p>洗盡鉛華始見金,褪去浮華歸本真</p> </body> </html>
效果圖:
㈥CSS - :before 偽元素
":before" 偽元素可以在元素的內容前面插入新內容。
下面的例子在每個 <h1>元素前面插入一幅圖片:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>:before</title> <style> h1:before {content:url(smiley.gif);} </style> </head> <body> <h1>This is a heading</h1> <p>The :before pseudo-element inserts content before an element.</p> <h1>This is a heading</h1> <p><b>注意:</b>僅當 !DOCTYPE 已經聲明 IE8 支持這個內容屬性</p> </body> </html>
效果圖:
㈦CSS - :after 偽元素
":after" 偽元素可以在元素的內容之后插入新內容。
下面的例子在每個 <h1> 元素后面插入一幅圖片:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>:after</title> <style> h1:after {content:url(smiley.gif);} </style> </head> <body> <h1>This is a heading</h1> <p>The :after pseudo-element inserts content after an element.</p> <h1>This is a heading</h1> <p><b>注意:</b>僅當!DOCTYPE 已經聲明 IE8支持這個內容屬性.</p> </body> </html>
效果圖:
㈧所有CSS偽類/元素