CSS tabs with :target

Using the :target pseudo-class to create tabs:

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.

Caveat: because the :target selector is part of yet-to-be-finalised CSS3 specification you’ll probably need to using a fairly bleeding-edge browser to view the demos.

I was impressed by the purity of the solution. I haven’t delved into CSS3 yet, although I’ve read that CSS3 selectors are powerful, but complicated. Here, :target seems simple, yet powerful.

Comments