Skip to content
Tutorials Center
My learning

Topics

CSS Reference ยท Pseudo-classes

The :target pseudo-class

Reference for the CSS :target pseudo-class: style the element whose id matches the URL fragment, with syntax, examples, usage notes and browser support.

The :target pseudo-class matches the element whose id equals the fragment of the current URL, the part after #. When the address is page.html#pricing, the element with id="pricing" matches.

It is useful for highlighting the section a reader jumped to from a table of contents, and for small no-JavaScript tricks such as tabs or modal panels driven by links.

CSS
:target {
  background: #fef9c3;
}

Try it

Highlight the jumped-to section

Syntax

CSS
:target { /* declarations */ }

No arguments; specificity (0,1,0). At most one element matches at a time, and none if the URL has no fragment or the id does not exist.

Syntax and arguments

Part Description
:target Matches the element selected by the document's URL fragment.
No arguments The pseudo-class is not functional.
Common forms section:target, :target h2, #panel:target { display: block; }

Usage notes

  • Fixed headers hide the target. When the browser scrolls to the element, a sticky header can cover it. Add scroll-margin-top to targetable elements.
  • Tabs and dialogs without JavaScript. Showing a panel only on :target works, but it changes the URL and history, and keyboard focus does not move automatically. Prefer real controls for important UI.
  • Highlight with animation. A short animation on :target fades attention to the destination without a permanent colour.
  • Back button. Each fragment change usually adds a history entry, so users can step back through the states.
  • Not the same as :focus. Following a fragment link scrolls to the element but does not guarantee keyboard focus on it.
  • Parent styling. To style an ancestor of the target, use :has(:target) on the container.

Browser support

Supported in every browser.