Pseudo-classes and pseudo-elements extend CSS selectors to style elements based on state or to create virtual elements that do not exist directly in the DOM. They enable powerful interactions, dynamic states, and content generation without additional markup.
What are pseudo-classes and pseudo-elements? Give examples.
Use guided tracks for structured prep, then practice company-specific question sets when you want targeted interview coverage.
Overview
Pseudo-classes and pseudo-elements allow developers to target special states or parts of elements beyond basic selectors. A pseudo-class represents a state (like hover or focus), while a pseudo-element targets a portion of content (like the first line or a generated content block).
Feature | Syntax | Purpose |
|---|---|---|
Pseudo-class |
| Targets elements based on user interaction or state. |
Pseudo-element |
| Selects a specific portion of an element or generates virtual content. |
Common Pseudo-Classes
a:hover {
color: #0ea5e9;
}
input:focus {
border-color: #2563eb;
}
li:first-child {
font-weight: bold;
}
These respond dynamically to user actions — hover changes color, focus highlights inputs, and first-child styles specific items in a list.
Common Pseudo-Elements
p::first-line {
font-weight: bold;
}
p::before {
content: '💡 Note: ';
color: #f59e0b;
}
p::after {
content: ' ✔';
color: #16a34a;
}
Pseudo-elements allow inserting generated content, emphasizing specific portions, or enhancing UX without modifying HTML.
Notable Differences
- Pseudo-classes use a single colon (
:), e.g.:hover. - Pseudo-elements use a double colon (
::) to distinguish structural parts, e.g.::before. - They can be combined — for instance:
a:hover::afteradds content only when hovered.
Practical Applications
- Creating tooltips with
::afterandcontent. - Animating buttons on
:hoveror:active. - Styling dynamic elements in forms and navigation bars.
Think of pseudo-classes as describing when an element behaves differently, and pseudo-elements as describing which part of it you’re styling or creating.
- Pseudo-classes define element states (e.g., :hover, :focus).
- Pseudo-elements define virtual parts (e.g., ::before, ::after).
- Use them to enhance interactivity and add decorative content without extra HTML.