What are pseudo-elements in CSS?
CSSThe short answer
Pseudo-elements let you style a specific part of an element without adding extra HTML. They use the :: syntax and create a "virtual" element that you can style. The most common ones are ::before and ::after, which insert content before or after an element's content.
::before and ::after
These create child elements that do not exist in the HTML:
.quote::before { content: '"'; font-size: 2rem; color: gray;}.quote::after { content: '"'; font-size: 2rem; color: gray;}<p class="quote">Hello, world</p><!-- Renders as: "Hello, world" with styled quotes -->The content property is required — without it, the pseudo-element does not appear.
Common use cases
Decorative elements:
.button::after { content: '→'; margin-left: 8px;}Custom list bullets:
li::before { content: '✓'; color: green; margin-right: 8px;}Overlay on images:
.card::after { content: ''; position: absolute; inset: 0; background: linear-gradient( transparent, rgba(0, 0, 0, 0.5) );}Clearfix (clearing floats):
.container::after { content: ''; display: table; clear: both;}Other pseudo-elements
::first-line — styles the first line of text:
p::first-line { font-weight: bold;}::first-letter — styles the first letter (drop caps):
p::first-letter { font-size: 3rem; float: left; margin-right: 4px;}::placeholder — styles input placeholder text:
input::placeholder { color: gray; font-style: italic;}::selection — styles text the user selects:
::selection { background: #ffeb3b; color: black;}Pseudo-elements vs pseudo-classes
- Pseudo-elements (
::before,::after) create virtual elements to style - Pseudo-classes (
:hover,:focus,:first-child) select elements based on state or position
/* Pseudo-class — selects existing element in a state */a:hover { color: red;}/* Pseudo-element — creates a virtual element */a::after { content: ' ↗';}Interview Tip
Show a ::before or ::after example with decorative content. Mention that content is required. Then explain the difference between pseudo-elements (::) and pseudo-classes (:). This distinction is the most common follow-up question.
Why interviewers ask this
This tests CSS knowledge beyond the basics. Pseudo-elements are used constantly for decorative styling without extra HTML markup. Interviewers want to see if you can use them for practical things like icons, overlays, and custom bullets.