CSS: expanding tabs effect

After all those months devoted to explore the inner depths of jQuery's effects, I actually missed something important. The fact is that sometimes we can actually achieve similar effects only with a little bit of CSS. This is the case of CSS tabbed menus. In this post I'm going to show you how to create a nice animation when a user hovers a tab with his mouse. When this happens, the current tab magically changes its size by gaining an extra height. We start with a markup like this:

<ul id="navigation">
 <li><a href="#">Home</a></li>
 <li><a href="#">Articles</a></li>
 <li><a href="#">About</a></li>
 <li><a href="#">Contact</a></li>

and with very simple styles:

body {
 margin: 0;
 padding: 0;
 font: 62.5% Arial, Helvetica, sans-serif;
 background: #fff;
 color: #333;

#navigation {
 height: 2em;
 font-size: 1.3em;
 margin: 1em 0;
 padding: 0 0 0 1em;
 list-style: none;
 border-bottom: 1px solid orangered;

#navigation li {
 float: left;
 height: 100%;
 margin-right: 0.5em;

So far we've only horizontally aligned our list items. Notice that the global height of our menu is 2em. Now it's time to stylize the links:

#navigation a {
 height: 1.5em;
 line-height: 1.5;
 display: block;
 padding: 0 1em;
 text-decoration: none;
 background: #d40;
 color: #fff;
 font-weight: bold;
 -moz-border-radius: 6px 6px 0 0;
 border-radius: 6px 6px 0 0;
 margin-top: 0.6em;

#navigation a:hover {
 background: orange;
 height: 2em;
 line-height: 2;
 margin-top: 0;

Did you see the trick? On a normal state, our links have an height which is less than the global height of the menu, plus a top margin that pushes them to the bottom of the menu, right on the bottom border of the whole container itself. To vertically align text we use the line-height property by setting its value on the same value of the height of each link. Then the magic: on hover we add more height and line height to our links so that they're exactly tall as their global container. Since we don't need the top margin anymore, we reset it to 0. You can see the final effect here.

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.