The ':target' pseudo-class

A URL normally points to a page. But when the URL ends in "#something" it targets a specific element in that page. Browsers typically try to make sure that the targeted element is visible and if possible at the top of the screen.

With the ':target' selector, you can add a specific style to the target element, so that it gets more attention.

But you can do more. You can hide or display elements based on whether they are the target or not. Below is an example. It shows a little menu with four items and each item is linked to some text. But at first no text is shown. Each item is a link to an element with a target ID (#item1, #item2...) and those elements are only visible when they are the target of the current URL.

Try to click on the menu items and also look at the location bar of the browser to see the current URL.

This is the element that corresponds to item 1. It should not be visible, unless you followed a link that explicitly targeted "#item1". If you jumped to item 2, then this element should be visible. This element is visible if you clicked on the third menu item. The element has a URL, that you can use elsewhere as well. You can put it in some other Web page and jump directly to this item. item 1 item 2 item 3 clear

Here is how it works. There are two important parts, the HTML source and the 'display' property. First the HTML document. It has some links and elements with corresponding IDs:

<p> <a href="#item1">item 1</a> <a href="#item2">item 2</a> <a href="#item3">item 3</a> <a href="#default">clear</a> <div class="items"> <p id="item1">... item 1... <p id="item2">... item 2... <p id="item3">... <p id="default"><!-- by default, show no text --> </div>

The style rules first hide all the Ps inside the DIV, but then override that for the P that is the current target:

div.items p {display: none} div.items p:target {display: block}

That's all. The example above goes on to add some colors, margins, borders, etc., so that it looks more like a menu. You can look at the source of this page to see how it is done.

Actually, we added ':not(:target)', to assure that only CSS3 browsers will hide the element. So the better rules are these:

div.items p:not(:target) {display: none} div.items p:target {display: block}