CSS Pseudo Elements
Pseudo-elements select a generated or special part of an element, such as ::before, ::after, ::first-line, and ::marker. Keep essential meaning in HTML.
A CSS pseudo-element selects a generated or special part of an element, not the element in a different state. ::before and ::after create extra boxes. ::first-line and ::first-letter style fragments of text. ::placeholder and ::marker style form hints and list markers. Double-colon syntax is the modern form.
before, after, and content
A ::before or ::after box exists only when content is set, including the empty string. They can take display, margin, and positioning. They cannot create a real button or supply the only accessible name.
.mode[aria-pressed="true"]::before {
content: "✓";
margin-inline-end: 0.5rem;
}
.quote::before { content: "“"; }
.quote::after { content: "”"; }Special parts of real elements
::first-line and ::first-letter can style an opening paragraph, with limits on which properties apply. ::placeholder styles hint text in inputs; it is not a label. ::marker styles the bullet or number of a list item. ::selection can tint highlighted text, still with contrast in mind.
article p:first-of-type::first-letter {
font-size: 2.4em;
float: inline-start;
line-height: 1;
padding-inline-end: 0.08em;
}
::placeholder { color: #5b6a66; }- Pseudo-classes select the element; pseudo-elements select a fragment or generated box.
- Decorative rules and shapes are a good fit for ::before.
- List numbers should usually remain real markers, not fake text in ::before, when the list is an ol.