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
| Criterion | Pseudo-element | Pseudo-class |
|---|---|---|
| What it does | Styles a part of the element or adds a virtual element | Describes the element's state or position |
| Example | ::before, ::after, ::first-letter | :hover, :first-child, :active |
| Occurs | Inside the element | On the element itself |
| Syntax | ::double_colon | :single_colon |
Examples of popular pseudo-elements
| Pseudo-element | Purpose |
|---|---|
::before | adds a virtual element before the content |
::after | adds a virtual element after the content |
::first-letter | selects the first letter |
::first-line | selects the first line of text |
::selection | styles 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 readyPremium
A concise answer to help you respond confidently on this topic during an interview.