Fluid CSS tabs

CSS tabs are better when they're fluid, because they can scale along with text and that's an important thing. Let's start with a basic structure like this:

<ul id="navigation">
 
  <li id="current"><strong>Home</strong></li>
  <li><a href="#">Articles</a></li>
  <li><a href="#">Test</a></li>
  <li><a href="#">Blog</a></li>
  <li><a href="#">About</a></li>
 
</ul>

Here you can see our basic structure. Now it's time to start adding some styles:

/* Tabs */

#navigation {
 margin: 0;
 padding: 0;
 height: 1.6em;
 list-style: none;
 border-bottom: 1px solid #0c0;
}

#navigation li {
 float: left;
 height: 100%;
 margin-right: 0.4em;
 background: #0c0 url("../img/topleft.png") no-repeat 0 0;
}

#navigation a:link,
#navigation a:visited,
#navigation strong {
 float: left;
 font-weight: bold;
 height: 100%;
 line-height: 1.6;
 padding: 0 0.5em;
 background: transparent url("../img/topright.png") no-repeat 100% 0;
 color: #fff;
}

#navigation strong {
 text-transform: uppercase;
}

This page shows the results we've got so far. As you can see, tabs have no explicit width declaration so that they can scale along with text. Now it's time to finish our work:

/* Hover effect */

#navigation li:hover {
 background: #24df00 url("../img/toplefthover.png") no-repeat 0 0;
}
#navigation a:hover {
 background-image: url("../img/toprighthover.png");
 background-position: 100% 0;
 background-repeat: no-repeat;
}
#navigation li#current:hover {
 background: #0c0 url("../img/topleft.png") no-repeat 0 0;
}

In this page, we've simply added an effect on hover by using the :hover pseudo-class on li elements. However, since Internet Explorer 6 supports this pseudo-class only on links, we have to use a couple of JavaScript lines to make it work:

function addHoverLi () {
 var navigation = document.getElementById("navigation");
 var li = navigation.getElementsByTagName("li");
 for (var i=0; i<li.length; i++) {
  if(!li[i].getAttribute("id")) {
  
  
   li[i].onmouseover = function () {
    this.style.background = "#24df00 url('../img/toplefthover.png') no-repeat 0 0";
   };
   li[i].onmouseout = function () {
    this.style.background = "#0c0 url('../img/topleft.png') no-repeat 0 0";
   }; 
  }
 }
}

window.onload = addHoverLi;

You can see the results here. As you can see, the achieved result is flexible, fluid and cross-browser.

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.