0
0
CssHow-ToBeginner · 3 min read

How to Use ::before in CSS: Syntax and Examples

The ::before pseudo-element in CSS inserts content before the content of a selected element. You use it with the content property inside a CSS rule to add text or symbols without changing the HTML.
📐

Syntax

The ::before pseudo-element is used with a selector to insert content before the element's actual content. It requires the content property to specify what to insert.

  • selector::before: Targets the element before its content.
  • content: Defines what is inserted (text, symbols, or empty string).
  • Other CSS properties like color, display, and position style the inserted content.
css
selector::before {
  content: "text or symbol";
  /* additional styles */
}
💻

Example

This example adds a red star before each list item to highlight it visually without changing the HTML.

css
ul li::before {
  content: "★ ";
  color: red;
  font-weight: bold;
}
Output
A bulleted list where each item starts with a red star symbol before the text.
⚠️

Common Pitfalls

Common mistakes include forgetting the content property, which makes the ::before not show anything. Also, using display incorrectly can hide the content. Remember, ::before works only on elements that can contain content.

css
/* Wrong: missing content property, nothing appears */
div::before {
  color: blue;
}

/* Right: content property added */
div::before {
  content: "Note: ";
  color: blue;
}
📊

Quick Reference

  • Use ::before to add content before an element's content.
  • Always include the content property.
  • Style the inserted content with CSS properties like color, font-size, and margin.
  • Works on elements that accept content (not void elements like img).

Key Takeaways

The ::before pseudo-element inserts content before an element's original content using the content property.
Always set the content property; without it, ::before will not display anything.
You can style the inserted content with CSS properties like color, font, and spacing.
::before works only on elements that can contain content, not on void elements like .
Use ::before to add decorative or informative content without changing HTML structure.