CSS僞元素用於向某些選擇器添加特殊效果。使用這些效果不需要使用JavaScript或任何其他腳本。僞元素的簡單語法如下所示−
selector:pseudo-element {property: value}
CSS類也可以與僞元素一起使用;
selector.class:pseudo-element {property: value}
最常用的僞元素如下−
Sr.No. | Value & Description |
---|---|
1 | :第一行 使用此元素可將特殊樣式添加到選擇器中文本的第一行。 |
2 | :第一個字母 使用此元素可向選擇器中文本的第一個字母添加特殊樣式。 |
3 | :之前 使用此元素在元素之前插入一些內容。 |
4 | :之後 使用此元素在元素後插入一些內容。 |
The :first-line pseudo-element
下面的示例演示如何使用:first-line元素向文檔中的第一行元素添加特殊效果。
<html> <head> <style type = "text/css"> p:first-line { text-decoration: underline; } p.noline:first-line { text-decoration: none; } </style> </head> <body> <p class = "noline"> This line would not have any underline because this belongs to nline class. </p> <p> The first line of this paragraph will be underlined as defined in the CSS rule above. Rest of the lines in this paragraph will remain normal. This example shows how to use :first-line pseduo element to give effect to the first line of any HTML element. </p> </body> </html>
它將產生以下連結&負;
The :first-letter pseudo-element
下面的示例演示如何使用:first letter元素向文檔中元素的第一個字母添加特殊效果。
<html> <head> <style type = "text/css"> p:first-letter { font-size: 5em; } p.normal:first-letter { font-size: 10px; } </style> </head> <body> <p class = "normal"> First character of this paragraph will be normal and will have font size 10 px; </p> <p> The first character of this paragraph will be 5em big as defined in the CSS rule above. Rest of the characters in this paragraph will remain normal. This example shows how to use :first-letter pseduo element to give effect to the first characters of any HTML element. </p> </body> </html>
它將產生以下黑色連結&負;
The :before pseudo-element
下面的示例演示如何使用:before元素在任何元素之前添加一些內容。
<html> <head> <style type = "text/css"> p:before { content: url(/images/bullet.gif) } </style> </head> <body> <p> This line will be preceded by a bullet.</p> <p> This line will be preceded by a bullet.</p> <p> This line will be preceded by a bullet.</p> </body> </html>
它將產生以下黑色連結&負;
The :after pseudo-element
下面的示例演示如何使用:after元素在任何元素之後添加一些內容。
<html> <head> <style type = "text/css"> p:after { content: url(/images/bullet.gif) } </style> </head> <body> <p> This line will be succeeded by a bullet.</p> <p> This line will be succeeded by a bullet.</p> <p> This line will be succeeded by a bullet.</p> </body> </html>
它將產生以下黑色連結&負;