CSS Pseudo-elements
A pseudo-element is a selector part that styles a piece of an element or inserts extra content. It uses two colons before its name.
Style the first letter
The ::first-letter pseudo-element targets the first letter of the paragraph. It gets a larger size and a red colour.
.intro::first-letter {
font-size: 24px;
color: red;
}Style the first line
The ::first-line pseudo-element targets the first line of the paragraph. That line is shown in bold.
.box p::first-line {
font-weight: bold;
}Insert content before a heading
The ::before pseudo-element inserts content before the heading. The content property sets the inserted text.
h2::before {
content: "ยป ";
}Example
.intro::first-letter {
font-size: 24px;
color: red;
}
.intro::first-line {
color: blue;
}
.box p::first-line {
font-weight: bold;
}
h2::before {
content: "ยป ";
}Key points
- Pseudo-classes use one colon in their names.
- Pseudo-elements use two colons in their names.
- The content property works only with ::before and ::after.
- The ::selection pseudo-element styles text a reader has highlighted.
- A pseudo-element can style just the first letter or the first line of a block.
In this example, the first letter of the intro paragraph is larger and red. The first line of the intro paragraph is blue. The first line of the paragraph inside the box is bold. A marker is inserted before the heading inside the box.
Try it Yourself
Edit the code, then press Run.
Runs in your browser โ the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.
Exercise
Which pseudo-element styles the first letter of a paragraph?