Jacob Rask

web stuff & who knows what else

Tabbed navigation with :target

It was not until recently I learned about the CSS3 pseudo-class target. In my old design, I linked elements to page headers via my Table of Contents and marked the headers in different ways — not visible in all browsers, but progressive enhancement.

In the process of redesigning my site, I wanted a small tabbed inter­face in a sidebar and started working on a jQuery script to accomplish that, when I realized I could use the target pseudo-class instead! Nothing more than the following is needed:

<ul>
 <li><a href="#tab1">Tab 1</a></li>
 <li><a href="#tab2">Tab 2</a></li>
 <li><a href="#tab3">Tab 3</a></li>
>/ul<

That is the navigation. And the targets:

<div id="tab1">Lorem ipsum dolor sit amet</div>
<div id="tab2">consectetur adipiscing elit</div>
<div id="tab3">Nullam vitae ligula eget erat suscipit sodales.</div>

The CSS to hide the content by default:

#tab1:not(:target), #tab2:not(:target), #tab3:not(:target) {
 display: none;
}

Using the not pseudo-class here makes sure the boxes are not hidden from browsers not supporting CSS3 properly. And to show them when the links are clicked:

#tab1:target, #tab2:target, #tab3:target {
 display: block;
}

Obviously, the Internet is big and when I googled, I realized I was hardly the first one to come up with this. Actually, it is even included in the W3C’s CSS Tips & Tricks. So, for a demonstration go there, and wait a couple of weeks to see it in action on my site as well.

Discussion

No comments yet

Add your comment to Tabbed navigation with :target through the comment form to the right.