CSS Introduction | CSS Selectors | Pseudo-elements
Pseudo-elements
A pseudo-element is used to select only a specific part of the corresponding HTML element.
CSS Pseudo-elements
| Pseudo-element | Description |
|---|---|
::first-letter |
Selects only the first letter of text. |
::first-line |
Selects only the first line of text. |
::before |
Used to insert another element immediately before the content of a specific element. |
::after |
Used to insert another element immediately after the content of a specific element. |
::selection |
Selects only the part of the element selected by the user. |
Syntax of Pseudo-elements
The syntax for using a pseudo-element is as follows.
Syntax
selector::pseudo-element-name {property: value;}
In CSS1 and CSS2, pseudo-classes and pseudo-elements were both written with a single colon(:).
In CSS3, pseudo-class notation and pseudo-element notation are separated.
Therefore, CSS3 uses one colon(:) for pseudo-classes and two colons(::) for pseudo-elements.
Representative CSS Pseudo-elements
Representative pseudo-elements commonly used in CSS are as follows.
::first-letter::first-line::before::after::selection
::first-letter
This pseudo-element selects only the first letter of text. It can be used only with block-type elements.
The properties available through this pseudo-element are as follows.
fontpropertycolorpropertybackgroundpropertymarginpropertypaddingpropertyborderpropertytext-decorationpropertytext-transformpropertyline-heightpropertyfloatpropertyclearpropertyvertical-alignproperty, only when thefloatvalue isnone
An example using this property is as follows.
<style>
p::first-letter { color: #FF4500; font-size: 2em; }
</style>
::first-line
This pseudo-element selects only the first line of text. It can be used only with block-type elements.
The properties available through this pseudo-element are as follows.
fontpropertycolorpropertybackgroundpropertyword-spacingpropertyletter-spacingpropertytext-decorationpropertytext-transformpropertyline-heightpropertyclearpropertyvertical-alignproperty
<style>
p::first-line { color: #FF4500; font-size: 2em; }
</style>
::before
This pseudo-element is used to insert another element immediately before the content of a specific element.
<style>
p::before { content: url("/examples/images/img_penguin.png"); }
</style>
::after
This pseudo-element is used to insert another element immediately after the content of a specific element.
<style>
p::after { content: url("/examples/images/img_penguin.png"); }
</style>
::selection
This pseudo-element is used to select only the part of the element selected by the user.
<style>
p::selection { color: #FF4500; }
</style>
Applying Multiple Pseudo-elements Together
Multiple pseudo-elements can be applied to one HTML element at the same time.
<style>
p::first-letter { color: #FFD700; font-size: 2em; font-weight: bold; }
p::first-line { color: #FF4500; }
</style>