Style generated parts without extra markup
Pseudo-elements let CSS target generated or selected portions of an element. ::before and ::after can add decorative content. ::first-letter styles the first typographic letter of a qualifying block. These generated parts should not carry information that readers need in order to understand or operate the page.
.tip {
position: relative;
padding-left: 1.5rem;
}
.tip::before {
content: "";
position: absolute;
left: 0;
top: 0.55em;
width: 0.6rem;
height: 0.6rem;
border-radius: 50%;
background: #2563eb;
}
.intro::first-letter {
font-size: 2em;
font-weight: 700;
}Apply .tip to a paragraph and .intro to another paragraph. The first receives a decorative dot; the second begins with an enlarged letter. The empty content string is necessary to generate the before box. Without content, it normally does not appear.
Content and positioning
The generated boxes participate in styling and can have backgrounds, borders and positions. An absolutely positioned before box uses the positioned .tip as its containing block in this example. Keep padding large enough so the dot does not overlap the actual text.
Do not hide meaning in CSS
A required field label must say it is required in accessible text or semantics. An error message should be actual content, not only a generated word. Screen-reader treatment of generated content varies by context, and users may disable or override author styles. CSS decoration should enhance content that already makes sense.
Limitations
Do not assume before/after works as a universal child-insertion mechanism on replaced elements such as images. Use a wrapper when decoration needs a predictable box. Pseudo-elements are not ordinary DOM nodes you can independently focus as controls.
Practice
- Turn the dot into a square by removing border-radius.
- Add a decorative underline with ::after and content:"".
- Disable the stylesheet and confirm the paragraph still contains its complete message.
- Why does ::before disappear when content is removed? The generated box is no longer created in the normal case.