CSS Pseudo Elements
CSS pseudo elements are used to add some special effects to selectors.
Syntax
Pseudo-element syntax:
selector:pseudo-element {property:value;}
CSS classes can also use pseudo-elements:
selector.class:pseudo-element {property:value;}
:first-line pseudo-element
"first-line" pseudo-element is used to add to the first line of text Set special styles.
Note: The "first-line" pseudo-element can only be used for block-level elements.
Note: The following properties can be applied to the "first-line" pseudo-element:
font properties
color properties
background properties
word-spacing
letter-spacing
text-decoration
vertical-align
text-transform
line-height
clear
:first-letter pseudo-element
The "first-letter" pseudo-element is used to set a special style to the first letter of text
Note: The "first-letter" pseudo-element can only be used for block-level elements.
Note: The following properties can be applied to the "first-letter" pseudo-element:
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
Pseudo-elements and CSS classes
Pseudo elements can be combined with CSS classes:
p.article:first-letter {color:#ff0000;}
<p class="article ">A paragraph in an article</p>
The above example will make the first letter of all paragraphs with class article turn red.
Multiple Pseudo-elements
Can be used in combination with multiple pseudo-elements.
In the example below, the first letter of the paragraph will be displayed in red and its font size will be xx-large. The rest of the text in the first line will be blue and appear in small caps.
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>php中文网</title> <style> p:first-letter { color:#ff0000; font-size:xx-large; } p:first-line { color:#0000ff; font-variant:small-caps; } </style> </head> <body> <p>You can combine the :first-letter and :first-line pseudo-elements to add a special effect to the first letter and the first line of a text!</p> </body> </html>
CSS - :before pseudo-element
":before" pseudo-element can insert new content before the content of the element.
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>CSS ::before 伪元素示例</title> <style type="text/css" media="all"> div::before { background: lightgreen; content: "张三"; } </style> </head> <body> <div>今天来学习知识</div> </body> </html>
CSS - :after pseudo-element
":after" pseudo-element can insert new content after the content of the element.
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>CSS ::after 伪元素示例</title> <style type="text/css" media="all"> div::after { background: lightgreen; content: "周末"; } </style> </head> <body> <div>今天是</div> </body> </html>