CSS Pseudo-Elements
Pseudo-elements allow you to style parts of an element that aren’t in the HTML — like the first letter of a paragraph or inserting decorative content before or after elements.
✅ Basic Syntax
selector::pseudo-element {
/* styles */
}
Double colons (
::
) is the standard syntax (CSS3+), but older browsers may still support single-colon:
for some pseudo-elements.
🧩 Commonly Used Pseudo-Elements
🔹 ::before
and ::after
Used to insert content before or after the actual content of an element.
h2::before {
content: "🌟 ";
}
p::after {
content: " 🔚";
}
You must define
content
, even if it’s empty (""
), for::before
or::after
to work.
You can combine them with layout styles like display
, position
, color
, etc.
🔹 ::first-letter
Targets only the first letter of a block element.
p::first-letter {
font-size: 150%;
color: crimson;
font-weight: bold;
}
🔹 ::first-line
Targets only the first line of text (depends on width and wrapping).
p::first-line {
font-weight: bold;
text-transform: uppercase;
}
🔹 ::selection
Styles the portion of text selected by the user (works in most modern browsers).
::selection {
background: yellow;
color: black;
}
You can also scope it:
p::selection {
background: lightblue;
}
💡 Real Use Cases
- Add icons or symbols with
::before
- Decorative lines or bullets with
::after
- Highlighting initial caps with
::first-letter
- Custom text highlight colors with
::selection
⚠️ Best Practices
- Don’t insert important content with
::before
or::after
— it’s not accessible to screen readers. - Use them mainly for visual decoration or enhancement.
- Prefer semantic HTML for real content.
📌 Bonus Example: Button with Arrow
button::after {
content: " →";
margin-left: 5px;
}
That’s it! Pseudo-elements are your secret design weapon — letting you enhance layout and design without touching the HTML.