MDN Web Docs

Syntax

css

:target {
  /* ... */
}

Description

When an HTML document loads, the browser sets its target element. The element is identified using the URL fragment identifier. Without the URL fragment identifier, the document has no target element. The :target pseudo-class allows styling the document's target element. The element could be focused, highlighted, animated, etc.

The target element is set at document load and history.back(), history.forward(), and history.go() method calls. But it is not changed when history.pushState() and history.replaceState() methods are called.

Examples

A table of contents

The :target pseudo-class can be used to highlight the portion of a page that has been linked to from a table of contents.

HTML

html

<h3>Table of Contents</h3>
<ol>
  <li><a href="#p1">Jump to the first paragraph!</a></li>
  <li><a href="#p2">Jump to the second paragraph!</a></li>
  <li>
    <a href="#nowhere">
      This link goes nowhere, because the target doesn't exist.
    </a>
  </li>
</ol>
<h3>My Fun Article</h3>
<p id="p1">
  You can target <i>this paragraph</i> using a URL fragment. Click on the first
  link above to try out!
</p>
<p id="p2">
  This is <i>another paragraph</i>, also accessible from the second link above.
  Isn't that delightful?
</p>

CSS

css

p:target {
  background-color: gold;
}
/* Add a pseudo-element inside the target element */
p:target::before {
  font: 70% sans-serif;
  content: "►";
  color: limegreen;
  margin-right: 0.25em;
}
/* Style italic elements within the target element */
p:target i {
  color: red;
}

Result

Specifications

Specification
HTML
# selector-target
Selectors Level 4
# target-pseudo

Browser compatibility

See also

Help improve MDN

Yes No

Learn how to contribute

This page was last modified on by MDN contributors.

Read the original on developer.mozilla.org ↗