Pseudo-Elements: ::before and ::after
7 min read
Inserting Generated Content
Pseudo-elements create virtual elements in the DOM that you can style with CSS. ::before inserts a child before the element's content; ::after inserts one after. They require a content property, which can be an empty string.
css
/* Decorative bullet before each list item */
.custom-list li::before {
content: "→";
color: #6366f1;
margin-right: 0.5rem;
}
/* Clearfix (legacy float technique) */
.clearfix::after {
content: "";
display: block;
clear: both;
}
/* Underline animation on hover */
.nav-link {
position: relative;
}
.nav-link::after {
content: "";
position: absolute;
bottom: -2px;
left: 0;
width: 0;
height: 2px;
background: #6366f1;
transition: width 0.3s ease;
}
.nav-link:hover::after {
width: 100%;
}Modern CSS uses double-colon syntax (::before) to distinguish pseudo-elements from pseudo-classes (:hover). Single-colon syntax (::before written as :before) still works for legacy reasons but is discouraged.
Ready to test yourself?
Practice CSS— quiz & coding exercises