:target

Avatar of Sara Cope
Sara Cope on (Updated on )

DigitalOcean provides cloud products for every stage of your journey. Get started with $200 in free credit!

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:

https://css-tricks.com/#voters

And this existed in the HTML:

<section id="voters">Content</section>

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 selecting the :target by ID:

#voters:target {
  /* Style it up */
}

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="#voters">Go To There</a>

<a href="http://example.com/#specific-part">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.

For instance, I once tried a variety of techniques to replicate functional CSS tabs, but ultimately decided using the checkbox hack was a better idea because it avoids the page-jumping issues. Ian Hansson at CSS Science has some examples of tabs as well. His third example uses :target, and absolutely positioned elements hidden above the top of the page to prevent page jumping behavior. It’s clever, but an overall perfect solution, because that would mean the page would jump upwards should the tabs be down further on a page.

Browser support

IEEdgeFirefoxChromeSafariOpera
9AllAllAllAllAll
Android ChromeAndroid FirefoxAndroid BrowseriOS SafariOpera Mobile
AllAllAllAllAll
Source: caniuse

More information