CSS tabs tutorial

In this tutorial I'll discuss with you a simple implementation of CSS tabs. We're going to create these tabs using background images, but be aware of the fact that the same effect can be achieved with the CSS3 border-radius property. Said that, we'll follow a step-by-step approach to help you understand the underlying techniques.

Step 1: the markup

We'll use an unordered list to wrap our navigation menu:

<ul id="navigation">

 <li><a href="#">Home</a></li>
 <li><a href="#">Contacts</a></li>
 <li><a href="#">About</a></li>

</ul>

We'll set a background image on each list item and link.

Step 2: the background images

Our background images are the following:

The left tab is narrower than the right tab, because we want the right tab to stretch and cover the entire clickable area without specifying a stated width on the items, thus allowing the tabs to change their widths while the font size changes. Each tab has been created with a black matte, because the background color of our menu is actually black. Each tab is 30 pixels tall.

Step 3: Global styles

Since our tabs are 30 pixels tall and given the fact that we want use ems for lengths, we have to set a base font size of 62.5%, so 1em equals to 10px:

body {
 margin: 0;
 padding: 0;
 font: 62.5% Arial, sans-serif;
}

#navigation {
 height: 3em;
 font-size: 1.2em;
 margin: 0;
 padding: 0 1em;
 background: #000;
 list-style: none;
}

Since our navigation menu has a font size of 1.2em, the actual height is 36 pixels. We've specified an height greater than the height of our tabs because we want to display the tabs at the very bottom of our menu. This will be clear in a moment.

Step 4: Styling the tabs

We first need to align the list items, push them down, then apply the left tab on them and finally stylize the links within them by adding the right tab to each link:

#navigation li {
 float: left;
 height: 2.5em;
 margin: 0.5em 0.5em 0 0;
 padding-left: 1em;
 background: url(tab-left.png) no-repeat;
}

#navigation a {
 float: left;
 height: 100%;
 display: block;
 line-height: 2.5;
 font-weight: bold;
 padding: 0 1em 0 0;
 color: #fff;
 text-decoration: none;
 background: url(tab-right.png) no-repeat 100% 0;
}

All elements have been floated to left. We use padding here to keep our tabs fluid and display the background images. Note how the list items have been lowered by specifying a top margin of 0.5em (that is, 6px). All elements have a stated height to prevent Internet Explorer 7 and lower from showing some bugs. Each link has a line height which equals its height so that the text is vertically centered. You can see the demo below.

Demo

Live demo

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.