Before vs After Pseudo Element: Key Differences and Usage
::before pseudo element inserts content just before the content of a selected element, while the ::after pseudo element inserts content immediately after it. Both are used to add decorative or functional content without changing the HTML structure.Quick Comparison
This table summarizes the main differences between ::before and ::after pseudo elements.
| Feature | ::before | ::after |
|---|---|---|
| Insertion point | Before the element's content | After the element's content |
| Common use | Add icons, decorations before text | Add icons, decorations after text |
| CSS property support | Supports all CSS properties | Supports all CSS properties |
| Content property | Requires content to display | Requires content to display |
| Stacking order | Appears in front of element's content by default | Appears behind element's content by default |
| Typical use case | Prefix text or symbols | Suffix text or symbols |
Key Differences
The ::before pseudo element inserts generated content immediately before the actual content inside an element. This means if you have a paragraph, the ::before content appears at the start inside that paragraph. Conversely, the ::after pseudo element inserts content right after the element's content but still inside the element.
Both require the CSS content property to display anything. Without it, they won't show. They are often used for adding decorative icons, quotes, or extra text without changing the HTML. The stacking order differs slightly: ::before content is in front of the element's main content by default, while ::after content appears behind.
In summary, the main difference is where the content is inserted relative to the element's original content: before or after it, but both remain inside the element's box.
Code Comparison
This example shows how to add a red star before a heading using ::before.
h2::before {
content: "★ ";
color: red;
font-size: 1.5rem;
}
h2 {
font-family: Arial, sans-serif;
}::after Equivalent
This example adds a green checkmark after the same heading using ::after.
h2::after {
content: " ✔";
color: green;
font-size: 1.5rem;
}
h2 {
font-family: Arial, sans-serif;
}When to Use Which
Choose ::before when you want to add content or decoration that logically comes before the element's main content, like a bullet, icon, or prefix. Use ::after when the added content should appear after, such as a suffix, symbol, or decorative flourish.
Both are great for enhancing UI without changing HTML. Use ::before for leading visuals and ::after for trailing visuals to keep your design clear and semantic.
Key Takeaways
::before inserts content inside an element before its original content.::after inserts content inside an element after its original content.content property to display anything.::before for prefixes or leading decorations.::after for suffixes or trailing decorations.