Before vs After in CSS: Key Differences and Usage
::before inserts content just before an element's actual content, while ::after inserts content immediately after it. Both are pseudo-elements used to add decorative or functional content without changing HTML.Quick Comparison
Here is a quick side-by-side comparison of ::before and ::after pseudo-elements in CSS.
| Feature | ::before | ::after |
|---|---|---|
| Position relative to element content | Before the content | After the content |
| Common use | Add icons, quotes, or decorations before text | Add icons, clear fixes, or decorations after text |
| Content property required? | Yes, must use content | Yes, must use content |
| Can style generated content | Yes | Yes |
| Affects element's box model? | No, does not affect layout size | No, does not affect layout size |
| Supported on replaced elements (like | No | No |
Key Differences
The ::before pseudo-element inserts generated content immediately before the content of the selected element. This means it appears inside the element but before any text or child elements. It is often used to add decorative icons, quotes, or labels without changing the HTML structure.
On the other hand, the ::after pseudo-element inserts content immediately after the element's content but still inside the element. It is commonly used for adding things like clear fixes, extra icons, or stylistic flourishes after the main content.
Both require the content property to display anything and can be styled with CSS properties like color, font, and positioning. Neither affects the element's actual size or layout, as they are purely visual additions inside the element's box.
Code Comparison
p::before {
content: "★ ";
color: gold;
font-weight: bold;
}
p {
font-size: 1.2rem;
color: #333;
}::after Equivalent
p::after {
content: " ★";
color: gold;
font-weight: bold;
}
p {
font-size: 1.2rem;
color: #333;
}When to Use Which
Choose ::before when you want to add content or decoration that appears before the main content of an element, like a bullet, icon, or label. Use ::after when you want to add something after the content, such as a decorative flourish, a clear fix for floated elements, or a suffix symbol.
Both are great for enhancing design without extra HTML, but pick based on whether the added content should appear before or after the element's original content visually.
Key Takeaways
::before inserts content before an element's main content inside the element.::after inserts content after an element's main content inside the element.content property to display anything.::before for prefixes or leading decorations, ::after for suffixes or trailing decorations.