Sub topic 7
Pseudo-elements
This chapter assumes you can write type, class, and ID selectors, know the difference between a pseudo-class and a selector list, and can read a specificity triple such as (0,1,1). A pseudo-element selects a part of an element, or generates content that does not exist in the HTML. You write it with a double colon, as in p::first-line.
What a pseudo-element is
A pseudo-class such as :hover picks out elements that are in a certain state. A pseudo-element such as ::before picks out a part of an element's rendering, or a box the browser creates for you.
The double-colon syntax separates the two. The CSS3 specification introduced :: so that authors could tell them apart. Browsers still accept the older single-colon form for four legacy pseudo-elements: :before, :after, :first-line, and :first-letter. Use :: in new code. Every other pseudo-element requires the double colon.
A pseudo-element comes at the end of a compound selector. You can write article p.lead::first-line, but you cannot write p::first-line.lead. Only one pseudo-element is allowed per selector, apart from a few special combinations such as ::part() with a state pseudo-class.
Generated content: ::before and ::after
::before and ::after create a box as the first or last child of the selected element. The box exists only if the content property is set. Without content, nothing is rendered.
.external-link::after {
content: " \2197";
font-size: 0.8em;
color: #555;
}
.required::before {
content: "* ";
color: #b00020;
}The first rule appends an arrow after any element with the class external-link. The content value can be a string, none, normal, a counter, an attr() call, or an image with url().
Some points to keep in mind:
- The generated box is not part of the DOM. You cannot select its text with the mouse in most browsers, and you cannot attach event listeners to it directly.
- Screen readers may or may not announce generated text, depending on the browser and the assistive technology. Do not put essential information in
content. - The generated box is a child of the selected element. For replaced elements such as
img,input, andbr, the browser does not generate::beforeor::afterboxes in the general case. - The default
displayof the box isinline. Setdisplay: blockordisplay: inline-blockif you need width, height, or vertical margins to apply.
A common use is a decorative shape, where content: "" creates an empty box that you size and paint.
.badge {
position: relative;
padding-left: 1.5rem;
}
.badge::before {
content: "";
position: absolute;
left: 0.4rem;
top: 50%;
width: 0.6rem;
height: 0.6rem;
border-radius: 50%;
background: seagreen;
transform: translateY(-50%);
}Using attr()
attr() reads an HTML attribute and uses its value as text. This is useful for tooltips and print styles.
a[href^="http"]::after {
content: " (" attr(href) ")";
}In a print stylesheet this shows the address after each external link. It also reuses the attribute selector from earlier chapters.
Typographic pseudo-elements
Two pseudo-elements select pieces of text inside a block.
::first-linematches the first formatted line of a block container. The set of lines changes when the viewport is resized, so the browser re-evaluates it.::first-lettermatches the first letter of the first line, including punctuation that precedes it, such as an opening quote.
.article > p:first-of-type::first-letter {
float: left;
font-size: 3.2em;
line-height: 0.9;
padding-right: 0.1em;
font-weight: 700;
}
.article > p:first-of-type::first-line {
font-variant: small-caps;
}Only a limited set of properties works on these two. ::first-line accepts font properties, color, background, and a few text properties. It does not accept margins or padding. ::first-letter also accepts margin, padding, border, and float, which is why drop caps work.
Other pseudo-elements
| Pseudo-element | What it selects |
|---|---|
| `::marker` | The bullet or number of a list item |
| `::selection` | The part of the document the user has highlighted |
| `::placeholder` | The placeholder text of an input |
| `::backdrop` | The layer behind a modal `dialog` or fullscreen element |
| `::file-selector-button` | The button inside an `input type="file"` |
| `::cue` | Captions in a WebVTT video track |
Each has its own limited list of allowed properties. For example, ::selection accepts color, background-color, and text decoration properties, but not layout properties.
li::marker {
color: darkorange;
font-weight: 700;
}
::selection {
background: #ffe08a;
color: #111;
}
input::placeholder {
color: #767676;
}Placeholder text needs enough contrast against its background to be readable. A pale gray placeholder is a common accessibility failure.
Specificity of pseudo-elements
A pseudo-element counts in the third column of the specificity triple, the same as a type selector. A pseudo-class counts in the second column, with classes and attributes.
p::first-line { color: blue; } /* (0,0,2) */
p.lead::first-line { color: green; } /* (0,1,2) */
.lead::before { color: red; } /* (0,1,1) */
li:hover::marker { color: orange; } /* (0,1,2) */Two things follow from this.
- A pseudo-element does not change which element a rule applies to. It only changes which part of that element is styled, so
p::first-lineandpdo not compete for the same target. They compete only when two rules target the same pseudo-element on the same element. - Adding a pseudo-element to a selector raises its specificity by one type-level step. If
.card::beforeneeds to beatdiv::before, the class already gives it (0,1,1) against (0,0,2).
A pseudo-element does not inherit from the originating element in the same way a child element does, but the generated box does inherit inheritable properties such as color and font-family from the element it belongs to. Setting color on .note therefore colors .note::before unless the pseudo-element sets its own value.
.note { color: green; }
.note::before {
content: "Note: ";
font-weight: 700;
}The "Note: " text is green because the generated box inherits color. The rule for ::before only sets font-weight.
Grouping and invalid selectors
Pseudo-elements follow the selector-list rules from the earlier chapter. Older browsers treated an entire list as invalid if one selector was unrecognized. That matters for vendor-prefixed pseudo-elements.
input::-webkit-input-placeholder { color: gray; }
input::-moz-placeholder { color: gray; }
input::placeholder { color: gray; }Keep the prefixed forms in separate rules. If you combined them with commas, a browser that does not recognize one of them would discard the whole rule. This is a place where a list is worse than repetition.
Common errors
- Forgetting
content. The rule matches, but no box appears. Addcontent: ""at minimum. - Using a pseudo-element on a replaced element.
img::afterusually does nothing. - Expecting JavaScript access.
querySelector("p::before")returns nothing. To read the computed value, usegetComputedStyle(element, "::before"). - Applying unsupported properties. A margin on
::first-lineis ignored without any warning. - Putting meaning in generated text. Search engines, copy and paste, and some screen readers may not see it.
Diagram of the box structure
Inspecting pseudo-elements
In browser developer tools, the Elements panel lists ::before and ::after as nodes beneath the element when they exist. You can click them and see the matched rules and the computed values. This is the quickest way to check whether content is set and which rule is winning, which connects to the debugging chapter later in this tutorial.
Exercise
A stylesheet has .card { color: navy; } and .card::after { content: " (new)"; }. What color is the text " (new)", and what is the specificity of the .card::after selector?
Show answer
The text is navy. The generated box is a child of .card and inherits color because the ::after rule does not set its own color. The specificity of .card::after is (0,1,1): one class and one pseudo-element.
Exercise
You write .tip::before { color: red; } and see no change on the page. Name the most likely cause and the fix.
Show answer
The rule does not set content, so no box is generated. Add content: ""; or a string such as content: "Tip: "; to the rule.