Sub topic 11
Generated content with ::before and ::after
This chapter assumes you know basic HTML, CSS rule syntax, class and attribute selectors, and the difference between a pseudo-class and a pseudo-element. Here you will learn how ::before and ::after create content that has no HTML tag, and where that content can go wrong.
What generated content is
::before and ::after are pseudo-elements. Each one creates a box inside the selected element. ::before is inserted before the element's real content. ::after is inserted after it. Both boxes are children of the element, not siblings, so they sit inside its padding and border.
The browser only creates the box when the content property has a value other than normal or none. Without content, the rule does nothing. This is the most common reason a new ::before rule appears broken.
.external::after {
content: " \2197";
}This appends an arrow (a space followed by the Unicode character U+2197) to every element with the external class. The HTML stays unchanged:
<a class="external" href="https://example.com">Example site</a>The structure of the generated boxes
The diagram shows where the generated boxes sit inside a selected element.
Some consequences follow from this structure:
- Replaced elements such as
img,input, andbrhave no content box for children, so::beforeand::afterusually do nothing on them. Put the pseudo-element on a wrapper instead. - The generated box is
display: inlineby default. Width and height have no effect until you changedisplay, or position the box absolutely or make it a flex or grid item. - The generated content is not in the DOM. You cannot select it with JavaScript's
querySelector, and users generally cannot select it with the mouse.
The content property
The content property accepts several kinds of values.
| Value | Example | Result |
|---|---|---|
| String | `content: "Note: "` | Inserts that text |
| Empty string | `content: ""` | Creates a box with no text, used for decoration |
| Escaped character | `content: "\2014"` | Inserts a Unicode character by its hex code |
| `attr()` | `content: attr(data-label)` | Inserts the value of an attribute on the element |
| `counter()` | `content: counter(step)` | Inserts the current value of a CSS counter |
| `url()` | `content: url(icon.svg)` | Inserts an image |
| `none` | `content: none` | Creates no box |
Strings are literal. You cannot put HTML tags in them. content: "<b>Hi</b>" shows the angle brackets as text.
A common mistake is to write a CSS escape that runs into the next character. "\2197 text" works because the space ends the escape, but the space is then consumed. To keep a visible space, write "\2197 text" with two spaces, or put the space before the escape as in the example above.
Decorative shapes with an empty string
An empty content string gives you a box you can style freely. Because it needs display: block or positioning, set that explicitly.
.card {
position: relative;
padding: 1rem;
border: 1px solid #ddd;
}
.card::before {
content: "";
display: block;
height: 4px;
background: #1a73e8;
margin: -1rem -1rem 1rem;
}The negative margins stretch the bar across the card's padding. Another common approach is absolute positioning, which removes the box from the normal flow:
.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: #2e7d32;
transform: translateY(-50%);
}The parent needs position: relative so the dot is placed against the badge and not some distant ancestor.
Pulling data from attributes
attr() lets the HTML supply the text. This is useful for short labels and tooltips that come from existing data.
abbr[title]::after {
content: " (" attr(title) ")";
font-size: 0.85em;
color: #555;
}With <abbr title="World Wide Web">WWW</abbr>, the page shows "WWW (World Wide Web)". In current browsers attr() is reliable inside content, and it returns a string. Using it in other properties, such as width, is newer and has less support.
Counters
Counters number things without extra markup. Two properties set them up: counter-reset creates the counter on a parent, and counter-increment adds to it on each item.
.steps {
counter-reset: step;
list-style: none;
padding: 0;
}
.steps li {
counter-increment: step;
margin-bottom: 0.75rem;
}
.steps li::before {
content: counter(step) ". ";
font-weight: 700;
}<ol class="steps">
<li>Open the file.</li>
<li>Edit the rule.</li>
<li>Save and reload.</li>
</ol>The three items are labeled 1., 2., and 3. If you only need numbers on an ol, the built-in numbering and ::marker (covered later in this tutorial) are simpler. Counters earn their place when you need nested numbering, such as 1.1 and 1.2, or numbering on elements that are not list items.
Clearfix and other layout uses
Before flexbox and grid, ::after was widely used to clear floats:
.clearfix::after {
content: "";
display: table;
clear: both;
}Today display: flow-root on the parent does this without a pseudo-element. You will still meet the clearfix in older code, so recognize it, but prefer flow-root in new work.
Accessibility of generated content
Generated content is exposed to the accessibility tree in most modern browsers. Screen readers may read it aloud, and the behavior differs between browser and screen reader pairs. Keep these rules in mind:
- Never put essential information in
content. Someone who disables author styles, uses a custom stylesheet, or reads the raw HTML will not see it. - Text in generated content cannot be translated by some tools and cannot be copied or searched reliably.
- Purely decorative content should be hidden from assistive technology when possible. Modern browsers support an alternative text after a slash:
content: "\2197" / "";means the arrow is shown but has an empty text alternative. Older browsers ignore the whole declaration, so provide a fallback line first. - Do not use
::beforeor::afterto carry an icon whose meaning matters, such as a warning symbol, unless the meaning is also in real text or an accessible label.
.external::after {
content: " \2197";
content: " \2197" / "";
}The first declaration is the fallback. A browser that understands the slash syntax uses the second one and treats the arrow as decoration.
Common pitfalls
- Forgetting
content. Nocontentdeclaration means no box. - Single versus double colon.
::beforeis the modern syntax. The single-colon:beforestill works for these older pseudo-elements, but use two colons to separate pseudo-elements from pseudo-classes. - Expecting width and height on an inline box. Set
display: block,inline-block, or position it. - Using them on
imgorinput. Replaced elements do not render the generated boxes in most browsers. - Trying to attach events or scripts. The generated box is not an element, so you cannot add listeners to it. A click on it targets the parent element.
- Pointer interference. An absolutely positioned overlay made with
::aftercan sit over a link or button and block clicks. Addpointer-events: noneif the overlay is only visual. - Layout surprises from flex or grid. In a flex or grid container,
::beforeand::afterbecome items themselves and take part in the layout, which can shift spacing or add an unexpectedgap.
.toolbar {
display: flex;
gap: 1rem;
}
.toolbar::after {
content: "";
flex: 1;
}Here the empty ::after becomes a flexible spacer item. It is a deliberate use of the behavior in pitfall 7, and the gap also applies between it and the previous item.
Specificity
A pseudo-element adds to specificity in the same way as a type selector, so .card::before has a specificity of one class plus one type. The cascade rules from the earlier chapter apply unchanged: .card::before beats ::before alone, and later rules win ties.
Exercise
A rule .note::before { color: red; font-weight: bold; } is meant to add the label "Note: " before each .note paragraph, but nothing appears. What is missing, and what would you add so the label shows with a trailing space?
Show answer
The rule has no content declaration, so the browser creates no box. Add content: "Note: "; to the rule. The trailing space inside the string is kept, so the label is separated from the paragraph text.
Exercise
You write .avatar::after { content: ""; width: 10px; height: 10px; background: green; } and no green square appears. Give two ways to fix it.
Show answer
The generated box is inline, so width and height are ignored. Either set display: block (or inline-block) on the pseudo-element, or make it position: absolute on a position: relative parent. Either change gives the box a size that can be painted.