CSS Pseudo-Elements
Learning Objectives
- Understand pseudo-elements and how they differ from pseudo-classes.
- Use ::before and ::after for decorative content.
- Style selected text, markers and placeholders.
- Avoid accessibility and content pitfalls.
1. What Is a Pseudo-Element?
A pseudo-element targets a particular part of an element or a generated part of its rendering. The double-colon notation distinguishes pseudo-elements from pseudo-classes.
2. ::before and ::after
.notice::before {
content: "Note: ";
font-weight: bold;
color: darkred;
}
.external-link::after {
content: " ↗";
}These pseudo-elements create generated content before or after an element's content. They generally require the content property to generate a box.
3. Decorative Shapes
.badge::before {
content: "";
display: inline-block;
width: 8px;
height: 8px;
margin-right: 6px;
border-radius: 50%;
background-color: green;
}Generated pseudo-elements are useful for decorative marks and visual enhancements.
4. ::first-letter and ::first-line
.intro::first-letter {
font-size: 2.5em;
font-weight: bold;
}
.intro::first-line {
color: navy;
}::first-letter styles the first typographic letter where applicable. ::first-line styles the first formatted line, which can change with layout and viewport size.
5. ::selection and ::marker
::selection {
background: navy;
color: white;
}
li::marker {
color: crimson;
}::selection styles selected text. ::marker styles list markers and applicable marker boxes.
6. ::placeholder and Form Styling
input::placeholder {
color: #666;
opacity: 1;
}::placeholder styles placeholder text. Placeholder text is not a replacement for a persistent, accessible form label.
7. Pseudo-Class vs Pseudo-Element
:hoveris a pseudo-class that matches a state.::beforeis a pseudo-element that targets generated content.- Modern syntax uses double colons for pseudo-elements, although some legacy single-colon forms remain supported.
Accessibility Considerations
Do not put essential instructions or critical information only in generated content. Assistive technologies may handle generated content differently. Use semantic HTML for meaningful content and CSS for decoration.