Skip to navigation

Styling Anchors with :target

When using page anchors (those parts of the page, such as headings, that you jump to with links), you can (theoretically) style the element that is the anchor itself by using the target pseudo class.

Using the following HTML:

<p>You can read all of content, or get straight to the <a href="#nittygritty">nitty-gritty</a>.</p>
<p>Alternatively, you can read the  <a href="#grittynitty">gritty-nitty</a>.</p>
<p>Or if you prefer, try the <a href="#wittyditty">witty ditty</a>.</p>
<!--[A whole load of content]-->
<h2 id="nittygritty">Nitty-Gritty</h2>
<h2 id="grittynitty">Gritty-Nitty</h2>
<h2 id="wittyditty">Witty-Ditty</h2>

And the following CSS:

h2 {
	color: #f60;

h2:target {
	color: white;
	background: #f60;

Not only will the browser jump to the required element (the anchor), it will highlight that element by changing its color to white and its background to orange.

But there was a "theoretically" thrown in there. Internet Explorer doesn't support the target pseudo-class (and neither does Opera at the time of writing), so this only works on a small number of browsers. target can still be used however as it can benefit those using capable browsers without adversely affecting those who aren't. The page anchors in the above code, for example, will still work in every browser, it's just that IE users won't have the highlighting bonus that others will have.

Like the focus pseudo-class, you can also mimic the target pseudo-class with some Suckerfish JavaScript.