CSS pseudo-classes and pseudo-elements – selectors that target element states or specific parts of an element without extra HTML. Useful for hover effects, focus styles, drop caps, and decorative content.
Pseudo-classes
Pseudo-classes are keywords added to selectors. They let you style elements based on state or condition – like conditional styling without JavaScript.
Common pseudo-classes
:hover: Styles an element when the pointer is over it.:focus: Applied when an element has focus, usually from tabbing or clicking.:active: Styles an element while it is being activated (clicked or pressed).:visitedand:link: Style links based on whether they have been visited.
Example usage
A few common patterns:
a:hover {
color: red;
}
input:focus {
border-color: blue;
}
button:active {
background-color: green;
}
Pseudo-elements
Pseudo-elements target specific parts of an element. They can insert content that does not exist in the HTML, which keeps markup cleaner.
Common pseudo-elements
::beforeand::after: Insert content before or after an element’s content.::first-lineand::first-letter: Style the first line or first letter of a text block.::selection: Style the portion of an element the user has selected.
Example usage
Decorative styling without extra markup:
p::first-letter {
font-size: 2em;
color: teal;
}
p::first-line {
font-weight: bold;
}
div::before {
content: "★";
color: gold;
}
div::after {
content: "★";
color: gold;
}
Advanced styles with pseudo-elements
Pseudo-elements are not limited to text styling. You can create shapes, overlays, and decorative patterns without adding elements to your HTML.
Creating shapes
A simple circle using ::before:
.shape::before {
content: "";
display: block;
width: 100px;
height: 100px;
background-color: skyblue;
border-radius: 50%;
}
That adds a circular shape before any element with the class .shape.
Adding decorative flourishes
A line under a heading:
.title::after {
content: "";
display: block;
width: 50%;
height: 2px;
background-color: black;
margin: 10px auto 0;
}
Responsive design with pseudo-classes
Pseudo-classes are useful in responsive design when you need styles that depend on user interaction or device type.
Hover effects on desktop vs mobile
Apply hover styles only on devices that support hover (avoid sticky hover states on touch screens):
@media (hover: hover) {
button:hover {
background-color: lightgreen;
}
}
Pseudo-classes and pseudo-elements add interactivity and decoration without bloating your HTML. Try a few on a test page – hover states, focus outlines, and a ::before decorative element are good starting points.

