Pseudo-Element (::before, ::after)

The Secret Sauce of CSS 

Ever wondered how some websites have cool decorative icons before links or fancy underlines under headings without extra HTML? The magic trick behind that is CSS pseudo-elements! 

Pseudo-elements ::before and ::after let you insert content before or after an element—without touching the HTML! Let’s explore how these hidden gems work.

What Are Pseudo-Elements? 

Pseudo-elements are special CSS selectors that let you style parts of an element without modifying the actual HTML. They are great for adding decorations, icons, and extra visual elements.

The two most common ones are:

Pseudo-Element What It Does
::before Adds content before an element. 
::after Adds content after an element. 

Note: Pseudo-elements don’t exist in the HTML—they are purely visual!

How to Use ::before and ::after

Basic Syntax:

.element::before {
  content: "Hello! ";
  color: red;
}

.element::after {
  content: " Goodbye!";
  color: blue;
}

This adds "Hello!" before and "Goodbye!" after .element

Adding Icons and Decorative Elements

Want to add an icon before a link? Easy!

a::before {
  content: "\1F517"; /* Unicode for đź”— link emoji */
  margin-right: 5px;
}

Now, every link has a little link emoji in front!

Styling Pseudo-Elements

Pseudo-elements can be styled just like regular elements!

h1::after {
  content: "";
  display: block;
  width: 50px;
  height: 5px;
  background: orange;
  margin-top: 10px;
}

This creates a small orange bar below every <h1>!

Best Practices for Pseudo-Elements

  • Use them for decoration only (not for important content).
  • Always define content, or they won’t appear!
  • Combine with animations for cool effects. 
  • Remember: One ::before and ::after per element

With ::before and ::after, you can add extra flair to your website without messy HTML.

Post a Comment

0 Comments