Sub topic 3
Generated Content and Text Pseudo-elements
Assume you know basic HTML, CSS selectors, combinators, and the difference between a class selector and an attribute selector.
Generated content with `::before` and `::after`
A pseudo-element selects a visual part of an element. ::before and ::after create generated content at the beginning or end of an element's contents. They usually need content, even when its value is an empty string.
.external::after {
content: " ↗";
}
.card::before {
content: "";
display: block;
height: 4px;
background: #1a73e8;
}Generated content is useful for decoration. It should not contain information that users must understand or operate.
Styling parts of text
::first-line styles the first displayed line, which can change when the viewport changes. ::first-letter styles the first letter of a block.
article p:first-of-type::first-letter {
float: left;
font-size: 3em;
line-height: 1;
margin-right: 0.1em;
}Markers, selections, and placeholders
Other pseudo-elements target browser-created parts:
li::marker {
color: #c00;
}
::selection {
background: #ffe58f;
color: #000;
}
input::placeholder {
color: #666;
}Combining pseudo-classes and pseudo-elements
A pseudo-class selects a state or condition. A pseudo-element styles a part of the match. Put the pseudo-class before the pseudo-element:
a:hover::after {
content: " ↗";
}
input:focus-visible {
outline: 3px solid #1a73e8;
outline-offset: 2px;
}Accessibility and common pitfalls
Keep a visible focus indicator. Prefer :focus-visible for keyboard-friendly focus styling, and do not remove the browser outline without replacing it. Do not communicate an error or status through color alone. Decorative generated content should not be the only way to understand a control. Screen readers may handle generated content differently across browsers.
Check whether content is present, keep selectors simple, and remember that pseudo-elements cannot replace real HTML when the content needs semantics.
Exercise
Which selector adds an arrow after an external link only when the link is hovered?
Show answer
a:hover::after { content: " ↗"; }