What are pseudo-elements in CSS?
The 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:
1.quote::before {2 content: '"';3 font-size: 2rem;4 color: gray;5}67.quote::after {8 content: '"';9 font-size: 2rem;10 color: gray;11}
1<p class="quote">Hello, world</p>2<!-- 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:
1.button::after {2 content: '→';3 margin-left: 8px;4}
Custom list bullets:
1li::before {2 content: '✓';3 color: green;4 margin-right: 8px;5}
Overlay on images:
1.card::after {2 content: '';3 position: absolute;4 inset: 0;5 background: linear-gradient(6 transparent,7 rgba(0, 0, 0, 0.5)8 );9}
Clearfix (clearing floats):
1.container::after {2 content: '';3 display: table;4 clear: both;5}
Other pseudo-elements
::first-line — styles the first line of text:
1p::first-line {2 font-weight: bold;3}
::first-letter — styles the first letter (drop caps):
1p::first-letter {2 font-size: 3rem;3 float: left;4 margin-right: 4px;5}
::placeholder — styles input placeholder text:
1input::placeholder {2 color: gray;3 font-style: italic;4}
::selection — styles text the user selects:
1::selection {2 background: #ffeb3b;3 color: black;4}
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
1/* Pseudo-class — selects existing element in a state */2a:hover {3 color: red;4}56/* Pseudo-element — creates a virtual element */7a::after {8 content: ' ↗';9}
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.