The :target pseudo-class matches the element identified by the document URL fragment. It responds to fragment navigation without application state, provided the target has a matching ID in the document.
CSS :target: confirm the section reached by a fragment
When to use it
A long incident report links from its contents list to individual sections. A short-lived visual highlight would require extra state code, but a persistent modest border on the current target can help readers verify arrival. Keep the heading readable and reserve space for a fixed toolbar with scroll-margin. The link and target ID must work without CSS. Test direct URLs, browser back and forward, duplicate or missing IDs, keyboard focus, high zoom, and print. :target shows which fragment is in the URL, not which section is currently centered in the viewport after manual scrolling. Do not use it as a full scrollspy or as the only confirmation for an important action. A fragment may target a heading rather than its containing section; choose the selector and HTML IDs accordingly. Avoid a dramatic animation that repeats when history navigation revisits the section.
.incident-report section[id] { border-inline-start: .25rem solid transparent; scroll-margin-block-start: 5rem; }
.incident-report section[id]:target { border-inline-start-color: #1c5e87; background: #edf5f8; }
@media print { .incident-report section[id]:target { background: transparent; border-inline-start-color: transparent; } }Cost and verification
The static style adds negligible rendering cost. The practical cost is keeping fragment IDs stable when content is edited or translated; broken deep links cannot be repaired by :target. If the report supports forced colors, check that the target cue remains perceptible or allow system colors to take over. A persistent highlighted section may be long, so avoid filling its entire background with a low-contrast tint that makes tables or links harder to read. Scroll-margin changes the preferred landing position but does not alter normal layout. Do not confuse the target with keyboard focus: a fragment jump may not put focus where an interactive workflow expects it.
Common Mistakes
- Do not use :target as a live viewport observer.
- Do not rely on a highlight when the fragment ID is missing or duplicated.
- Do not replace keyboard focus handling with fragment styling.
Connected lessons
- CSS Property Decisions
- CSS scroll offsets: reveal anchors below a persistent header
- CSS link decoration and states: preserve a visible navigation cue
- HTML anchors: use href for navigation and stable fragment targets
