Pseudo-elements in CSS


A CSS Pseudo-element allows you to style specific parts of an element without adding any extra HTML markup. It creates virtual elements like first letter, first line, or content before/after an element.

Syntax

 selector::pseudo-element {
  property: value;
}

Modern syntax uses double colons (::) to distinguish pseudo-elements from pseudo-classes (:), but older browsers still support a single colon (:) for backward compatibility.

css-pseudo-elements


Commonly Used Pseudo-elements

Pseudo-element Description
::before Inserts content before an element’s content
::after Inserts content after an element’s content
::first-letter Styles the first letter of a block element
::first-line Styles the first line of a block element
::selection Styles the part of text highlighted by the user

Example : Pseudo-elements

::before

Adds content before an element’s content.

 

h1::before {
  content: "*";
  color: red;
} 

::after

Adds content after an element’s content.

 

h1::after {
  content: "*";
  color: green;
}

::first-letter

Styles the first letter of an element.

 

p::first-letter {
  font-size: 200%;
  color: crimson;
}

Example

<!DOCTYPE html>
<html>
<head>
  <style>
    h1::before {
      content: "👉 ";
      color: red;
    }

    h1::after {
      content: " ✅";
      color: green;
    }

    p::first-letter {
      font-size: 200%;
      color: crimson;
    }

    p::first-line {
      font-weight: bold;
      color: navy;
    }

    ::selection {
      background: yellow;
      color: black;
    }
  </style>
</head>
<body>

<h1>Pseudo-element Example</h1>

<p>This paragraph shows how the first letter is larger and crimson, and the first line is bold and navy. Try selecting this text to see the selection effect.</p>

</body>
</html> 

Advantages

  • Adds content or styling without altering the HTML structure.
  • Useful for decorative purposes or text formatting.
  • Eliminates the need for extra , <div>, or other elements.

Pseudo-class vs Pseudo-element

Feature Pseudo-class (:) Pseudo-element (::)
Targets State of an element Part of an element
Example a:hover p::first-letter
Purpose Interaction/condition-based Structural/format-based



OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.