While pseudo-classes target elements in specific states, Pseudo-Elements create virtual DOM elements or target specific sub-parts of an existing element. Under CSS3 standards, pseudo-elements are written with a double colon (::) to distinguish them from pseudo-classes.
The ::before and ::after pseudo-elements allow developers to insert cosmetic, decorative content into an element without cluttering the semantic HTML document with extra <span> or <div> tags.
A pseudo-element will NOT render unless you provide the content: ""; property! Even if you set width, height, and background color, omitting content causes the browser to ignore the pseudo-element completely.
/* Heading with a stylish red accent bar */
h2.ribbon {
position: relative;
padding-left: 18px;
color: #0f172a;
}
h2.ribbon::before {
content: "";
position: absolute;
left: 0;
top: 50%;
transform: translateY(-50%);
width: 6px;
height: 24px;
background-color: #d22b2b;
border-radius: 3px;
}
| Pseudo-Element | Standard Example | Visual Styling Capability |
|---|---|---|
| ::first-letter | p::first-letter { font-size: 200%; color: #d22b2b; } |
Styles the initial letter of a block of text, perfect for newspaper drop-caps. |
| ::first-line | p::first-line { font-weight: bold; } |
Styles the dynamically wrapped first line of text on screen. |
| ::selection | ::selection { background: #d22b2b; color: #fff; } |
Styles text highlighted by user cursor dragging across the page. |
| ::marker | li::marker { color: #d22b2b; font-size: 1.2em; } |
Customizes the bullet point dot or number of <li> elements. |
| ::placeholder | input::placeholder { color: #94a3b8; } |
Styles the ghost placeholder text inside form inputs and textareas. |
Question: What is the difference between single colon (:hover) and double colon (::before) syntax?
Answer: Under the W3C CSS3 specification, a single colon indicates a pseudo-class (an element state, like :hover), while a double colon denotes a pseudo-element (a virtual element or sub-part, like ::before). Browsers still accept single colon for legacy pseudo-elements (like :before) for backward compatibility.
Boost your CSS and front-end development proficiency by exploring these closely connected topics:
Understand margins, borders, padding, content and the universal box-sizing fix.
Master 1D alignment, justify-content, align-items, flex-wrap and responsive flow.
Build powerful two-dimensional grid layouts with template areas and fr units.
Eliminate styling conflicts and master selector weights from 0,0,0,1 to !important.