0
0
CssHow-ToBeginner · 3 min read

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 content
  • content: required property to define what is inserted
  • Other CSS properties like color, display, and position style 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

PropertyDescription
::afterSelects a virtual element after the selected element's content
contentDefines what is inserted (text, symbols, empty string)
displayControls layout of the inserted content (inline, block, inline-block)
positionAllows positioning the inserted content relative to the element
colorSets 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.