Skip to main content

What is a pseudo-element? How does a pseudo-element differ from a pseudo-class?

A pseudo-element is a selector that lets you select and style a specific part of an element or create a virtual element that does not exist in the HTML markup. A pseudo-element effectively adds a "virtual" piece of content or highlights part of the text (a letter, a line, and so on).

Example:

css
p::first-letter { font-size: 40px; }

::first-letter is a pseudo-element that affects only the first letter of a paragraph.


How a pseudo-element differs from a pseudo-class

CriterionPseudo-elementPseudo-class
What it doesStyles a part of the element or adds a virtual elementDescribes the element's state or position
Example::before, ::after, ::first-letter:hover, :first-child, :active
OccursInside the elementOn the element itself
Syntax::double_colon:single_colon

Pseudo-elementPurpose
::beforeadds a virtual element before the content
::afteradds a virtual element after the content
::first-letterselects the first letter
::first-lineselects the first line of text
::selectionstyles the text selection

Example with ::before:

css
h1::before { content: "* "; color: gold; }

Short summary

  • Pseudo-class (:), selects an element by state or position
  • Pseudo-element (::), selects a part of an element or creates a virtual element

They are often used together, pseudo-classes for reactions, pseudo-elements for decoration and content.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.