The :target CSS pseudo-class

CSS3 also introduced :target; a powerful pseudo-class which can reduce the need for scripting in interactive widgets.

:target – The target pseudo class is used in conjunction with ID’s, and match when the hash tag in the current URL match that ID. So if you are at URL www.yoursite.com/#home then the selector #home:target will match. Then can be extremely powerful. For example, you can create a tabbed area where the tabs link to hash tags and then the panels “activate” by matching :target selectors and (for example) using z-index to move to the top, or just to highlight a section of your content.

:target Browser Support

Because we are talking about CSS3, it’s supported by all modern browsers excluding IE, from 6 to 8. Disappointing as usual, but this fact shouldn’t stop you using it. However, IE9 supports the :target pseudo-class.

Internet Explorer Firefox
6.0 7.0 8.0 9.0 1.0 1.5 2.0 3.0 3.5
None None None Full Full Full Full Full Full
Safari Opera Chrome
1.3 2.0 3.1 4.0 9.2 9.5 10.0 2.0
Buggy Buggy Full Full None Full Full Full

How can you use :target?

This pseudo-class can be styled, just like we use to style the :hover, :active or :focus pseudo-classes on links. Much like the previous ones, :target is used during certain interactions with the website. Specifically, when applied to a fragment identifier as in this example: http://www.yoursite.com/#portfolio.

Demonstration

On this demo I am going to make an example of when to use :target. The purpose of the demo is to show you how :target can improve your website usability.

View Demo

The HTML markup

Let’s look at a snippet of the html document. Below we have a list of 4 links and also the same amount of blocks. The important part here is that every element or div must have an id as an identifier.

 

The CSS

We can use the :target attribute to highlight active sections, e.g

Below you can find the result, when a list element it’s clicked, the corresponding block will change background.

And That’s All! The :target selector offers further versatility possible to create dynamic effects in HTML5 and CSS without using JavaScript.

Thanks.