Last updated on

The :target pseudo selector in CSS matches when the hash in the URL and the id of an element are the same. For example, if the current URL is:

And this existed in the HTML:

<section id="categories"> 

This selector would match:

:target {
   background: yellow;

And that section element would have a yellow background.

With that generic of a selector (matching anything that happens to be the target), if the URL changed to end in #faq and there was another element with an ID of faq, that selector would match again and the #faq element would have a yellow background.

You could limit it by being specific about which elements you want to target, like

#categories:target {


When would you use this?

One possibility is when you want style with “states.” When the page has a certain hash, it’s in that state. It’s not quite as versatile as manipulating class names (since there can only be one and it can only be related to one element) but it’s similar. Anything you could do changing a class to change state you could do when the element is in :target. For instance: change colors, change position, change images, hide/show things, whatever.

I’d use these rules-of-thumb for when :target is a good choice:

  1. When a “state” is needed
  2. When the jump-down/hash-link behavior is acceptable
  3. When it’s acceptable to affect the browser history

How do you get hashes in URLs?

The most common way is by a user clicking a link which includes a hash. Could be an internal (same-page) link or a fully qualified URL that happens to end with a hash and value. Examples:

<a href="#categories">Go To There</a>

<a href="">Go To There</a>

Jumping Behavior

Regardless if it’s a same-page link or not, the browser behavior is the scroll the page until that element is at the top of the page. Or, as far as it can if it can’t scroll that far. This is rather important to know, because it means exploiting this “stated” behavior is a bit tricky/limited.

Browser Support

Chrome Safari Firefox Opera IE Android iOS
Any 1.3+ 1.3+ 9.5+ 9+ 2.1+ 2+

Leave a Reply

Your email address will not be published. Required fields are marked *