Quiz

Describe pseudo-elements and discuss what they are used for.

Topics
CSS

TL;DR

A pseudo-element selects a part of an element or a generated box that is not represented by a separate HTML element, such as ::first-letter, ::marker, ::selection, ::before, or ::after. Use pseudo-elements for presentation and generated decoration, not for essential content or controls. Pseudo-classes such as :hover and :focus-visible instead select an existing element in a particular state.


Describe pseudo-elements and discuss what they are used for.

Pseudo-elements extend a selector with ::name and let CSS address content that ordinary element selectors cannot target directly.

Common uses

  • ::before and ::after generate child-like boxes for decoration.
  • ::first-letter and ::first-line style typographic fragments.
  • ::marker styles a list item's marker.
  • ::selection styles user-selected text.
  • Form-control pseudo-elements expose browser-defined parts where supported.
.external-link::after {
content: '';
display: inline-block;
width: 0.75em;
height: 0.75em;
margin-inline-start: 0.25em;
background: currentColor;
mask: url('/icons/external-link.svg') center / contain no-repeat;
}
li::marker {
color: rebeccapurple;
}

Generated content is not semantic HTML

::before and ::after do not create DOM elements, cannot replace a real button or link, and have inconsistent exposure to accessibility APIs. Keep important labels, instructions, and status messages in HTML. Decorative generated content should not be the only way meaning is conveyed.

Use the double-colon syntax for pseudo-elements. Browsers retain the old single-colon form for the original :before, :after, :first-line, and :first-letter names for compatibility, but new pseudo-elements use ::.

Further reading

Exercises

Check your understanding
Beta
Check your understanding Exercise
Check your understanding Exercise

Which selectors target pseudo-elements rather than element states? Select all that apply.