O'Reilly

CSS :target

By on  

One interesting CSS pseudo selector is :target.  The target pseudo selector provides styling capabilities for an element whose ID matches the window location's hash.  Let's have a quick look at how the CSS target pseudo selector works!

The HTML

Assume there are any number of HTML elements with a given ID:

<h2 id="section1">Section 1</h2>

<h2 id="section2">Section 2</h2>

Take note of the ID values of the elements above -- to trigger the :target pseudo selector, the window.location.hash will need to match.

The CSS

The :target pseudo selector may be applied to classes, tags, or any other selector:

/* would apply to all targetted elements */
:target {
	color: #000;
}

/* applies to H2's */
h2:target {
	color: #f00;
}

When the window.location.hash is section2, the element color will become red and underlined.  Simple!  Much like you can animate elements upon hover or even between media queries, you could even animate the element when targeted; Chris Coyier provides an excellent example of target animating.

:target is neat but I haven't seen it abused to do anything groundbreaking.  For a site that doesn't strive for ultimate dynamism, however, the :target pseudo selector could add a bit of native class when using window hashes.

Track.js Error Reporting

Upcoming Events

Recent Features

  • Create a Sheen Logo Effect with CSS

    I was inspired when I first saw Addy Osmani's original ShineTime blog post.  The hover sheen effect is simple but awesome.  When I started my blog redesign, I really wanted to use a sheen effect with my logo.  Using two HTML elements and...

  • Create a CSS Cube

    CSS cubes really showcase what CSS has become over the years, evolving from simple color and dimension directives to a language capable of creating deep, creative visuals.  Add animation and you've got something really neat.  Unfortunately each CSS cube tutorial I've read is a bit...

Incredible Demos

  • MooTools Window Object Dumping

    Ever want to see all of the information stored within the window property of your browser? Here's your chance. The XHTML We need a wrapper DIV that we'll consider a console. The CSS I like making this look like a command-line console. The MooTools JavaScript Depending on what you have loaded...

  • Dynamically Create Charts Using MooTools MilkChart and Google Analytics

    The prospect of creating graphics charts with JavaScript is exciting. It's also the perfect use of JavaScript -- creating non-essential features with unobtrusive scripting. I've created a mix of PHP (the Analytics class), HTML, and MooTools JavaScript that will connect to Google Analytics,...

Discussion

  1. Hi David,

    I think one of the reason that make this technique hard to use in large websites could be the unability to create multi-level lists with this :

    Example :

    Four links in 2 categories
    – #category1-link1
    – #category1-link2
    – #category2-link1
    – #category2-link2

    Category 1

    Link1
    Link1

    Category 2

    Link1
    Link1

    Then, this way you can style the 2nd-level links (#categoryX-linkY), but how can you know how to style #category1 and category2? You can’t. Because #category1:target and #category2:target never happen.

    The only solution I see is parent selectors but it’s not even implemented in browsers yet.

  2. First thing for :target use that comes to mind “tabs” nothing else…

  3. SVG stacks use :target to great effect. Too bad they’re not more widely useful yet.

  4. Another valid use I’ve come across is accordion widgets.

  5. Yin

    Not sure if I can think of a good use for this yet, but it’s great to read about it. I think the code:

    h2:target {
    color: #f00;
    }

    should be

    h2:target {
    background: #f00;
    }

  6. very good idea!
    Even for dynamic pages.

    http://jsfiddle.net/b3YEk/17/

  7. The only problem right now is bad support in IE, which doesn’t remove or re-add the pseudo-class when you use back and forward navigation.

  8. Joe

    I was aware of :target, but this has prompted me to use it for a great use case: help docs.

    Now I can just link people to the ID of a specific part of a help guide and it will automatically highlight the relevant passage.

    Perfect.

  9. @DrDeath, quite limited imagination. How about a FAQ Page that has all the questions first and the answers at the bottom? If there are many, using :target to highlight the answer for the question that you clicked would make it easy, since several answers would be shown on the screen at the same time.

    • Wayne

      @Gabriel Rodriguez, your imagination may well be a tad limited too. Instead of having all the answers displayed and highlighting the relevant ones, why not display just the relevant answer? (Mind you, I haven’t actually tested this theory of mine yet. But it seems like it should work, unless I’ve misunderstood how :target functions.)

  10. @Gabriel Rodriguez i think accordion better for faq page

  11. Using :not(:target) gives you even more flexibility, because you can also style the elements that are not :target, and even apply transitions to them :)

    http://jsfiddle.net/SchizoDuckie/fzZ9d/

    • Wayne

      Sweet demo! Thanks for sharing.

      Incidentally, not that it would be appropriate for that demo (because it definitely wouldn’t), did you know that setTimeout can be used without a second parameter? In other words, it can be used just to set the execution order of functions. (Only recently did I discover that little tidbit.)

  12. When do you guys expect Internet Explorer will have full support for these kind of elements?

    • SchizoDuckie

      Probably somewhere between 2020 and 2030. And then you’ll still have to wait for adoption rate…

  13. Leandro

    Hey SchizoDuckie, looks like you’re wrong! haha (after a long time) http://caniuse.com/#search=%3Atarget

    internet explorer finally over, microsoft will implement your new browser, now, the things go more faster

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!

Recently on David Walsh Blog

  • Free Download: Font Bundle Featuring 17 Incredible Typefaces

    The only thing we love more than a good font, is a good free font. So we’ve combed the Web for some of our favorite free fonts, and gathered them here in a single download. You’ll find a variety of useful typefaces, from highly geometric designs...

  • OâReilly Velocity Conference â Amsterdam

    My favorite front-end conference has always been O'Reilly's Velocity Conference because the conference series has focused on one of the most undervalued parts of client side coding:  speed.  So often we're so excited that our JavaScript works that we forget that speed, efficiency, and performance are just as important. The next Velocity...

  • CanIUse Command Line

    Every front-end developer should be well acquainted with CanIUse, the website that lets you view browser support for browser features.  When people criticize my blog posts for not detailing browser support for features within the post, I tell them to check CanIUse:  always up to date, unlike...

  • Generating Alternative Stylesheets for Browsers Without @media

    If your CSS code is built with a mobile-first approach, it probably contains all the rules that make up the "desktop" view inside @media statements. That's great, but browsers that don't support media queries (IE 8 and below) will simply ignore them, ending up getting the...

  • Serve a Directory with PHP

    Many developers have a giggle at PHP, even looking down at the language, but let's be honest:  most of our blogs are powered by it (WordPress) and it's a great language to dabble around with.  I cut my teeth on PHP, though I prefer to avoid PHP these days. But...