How to Use ::after in CSS: Simple Guide and Examples
The
::after pseudo-element in CSS lets you insert content after an element's content without changing the HTML. You use it with the content property inside a selector to add text, icons, or decorations after the element.Syntax
The ::after pseudo-element is used with a selector followed by ::after. Inside its block, you must set the content property to specify what to insert. You can add text, symbols, or even empty content for styling.
selector::after: targets the element's after contentcontent: required property to define what is inserted- Other CSS properties like
color,display, andpositionstyle the inserted content
css
selector::after {
content: "text or symbol";
/* other styles */
}Example
This example shows how to add a red asterisk * after a label to indicate a required field. The ::after inserts the asterisk without changing the HTML.
css
label::after {
content: " *";
color: red;
font-weight: bold;
}
/* HTML example for context:
<label>Name</label>
*/Output
The word "Name" followed immediately by a red bold asterisk (*) in the browser.
Common Pitfalls
One common mistake is forgetting to set the content property, which makes the ::after not show anything. Another is using display: inline when you want to style block-level content, so use display: inline-block or block if needed. Also, ::after works only on elements that can contain content, so it won't work on void elements like <img>.
css
/* Wrong: missing content, no output */ button::after { color: blue; } /* Right: content set, visible output */ button::after { content: " ✔"; color: blue; }
Quick Reference
| Property | Description |
|---|---|
| ::after | Selects a virtual element after the selected element's content |
| content | Defines what is inserted (text, symbols, empty string) |
| display | Controls layout of the inserted content (inline, block, inline-block) |
| position | Allows positioning the inserted content relative to the element |
| color | Sets the color of the inserted content |
Key Takeaways
Always set the content property when using ::after to make it visible.
::after inserts content after an element without changing HTML structure.
You can style the inserted content with CSS properties like color and display.
::after does not work on void elements like
or .
Use ::after for adding decorative or informative content without extra markup.