The :target pseudo-class in CSS

A few weeks ago, we were working on a table of contents for the Vanilla JS Academy. It’s a script that dynamically creates a list of skip links from the headings in a document. It was a great opportunity to implement the :target pseudo-class, which is a neat CSS selector you might not know about.

As they explain in the MDN Web Docs:

The :target CSS pseudo-class represents a unique element (the target element) with an id matching the URL’s fragment.

  1. An example
  2. Browser support
  3. Learn more

An example

Notice that I added a list of skip links above this heading.

When you click on one, your browser will scroll to that heading. The heading will be highlighted with a yellow background.

That’s because I have the following rule in my stylesheet:

:target {
  background: #ff0;
}

Browser support

The :target pseudo-class is supported back to IE9. You can check out the compatibility data on Can I Use.

Learn more

The following pages in the MDN Web Docs are helpful:


If you have questions, feedback, or any other suggestions, please do email me. I'd love to hear from you!