CSS Pseudo-elements let you style specific parts of an element or inject virtual elements (::before, ::after) without changing the actual HTML.
Common pseudo-elements:
::before – Inserts content before the element.::after – Inserts content after the element.::first-letter – Styles the first letter of a block element.::first-line – Styles only the first line of text.::before and ::after require the content property to be visible.:: for pseudo-elements.The basic syntax for pseudo-elements is:
/* Basic pseudo-element syntax */
selector::pseudo-element {
property: value;
}
Example:
p::first-letter selects only the first character of a paragraph.p::first-line selects only the first rendered line..btn::before can add an icon before a button label.
/* Style different parts of a paragraph using pseudo-elements */
p::first-letter {
font-size: 200%;
color: red;
}
p::first-line {
font-weight: bold;
}
p::before {
content: "? ";
color: green;
}
p::after {
content: " ✔";
color: blue;
}
Here is a full HTML + CSS example:
<!-- HTML: one simple paragraph -->
<p class="highlighted-text">
This is a sample paragraph where the first letter is styled,
the first line is bold, and it shows icons before and after.
</p>
/* CSS: apply multiple pseudo-elements */
.highlighted-text::first-letter {
font-size: 200%;
color: red;
}
.highlighted-text::first-line {
font-weight: bold;
}
.highlighted-text::before {
content: "? ";
color: green;
}
.highlighted-text::after {
content: " ✔";
color: blue;
}
The result looks similar to this:
? This is a sample paragraph where the first letter is red and enlarged, the first line is bold, and it ends with a blue check mark ✔
::before) appears before the text.::first-letter).::first-line).::after.::before/::after with absolute positioning.::before and ::after to add decorative content or icons without modifying the HTML.::first-letter with drop cap styling for elegant article or blog intros.content is required for ::before and ::after to display.::first-letter to look like a “drop cap” in magazines.::before and ::after to add custom symbols or emojis around a heading (for example, ⭐ <h2> ⭐).::first-line; adjust width and font size to see how the first line changes.::before for an icon and ::after for a badge (like “NEW”).