CSS: tabs and background image size

In CSS, a background image set on an element can be either constrained or unconstrained. This particular algorithm applies to the width of background images. When an element has no stated width, the background image is unconstrained. Conversely, when an element has a stated width, the background image is constrained. Consider the example of CSS tabs: usually we use background images that are much bigger than the actual width of the tabs. This is where this algorithm comes into play. If we omit to specify a width for the tabs and we use only some padding, then we'll see the background image filling the tab without problems.

This technique applies also to rounded corners made with images: you specify an element without width, apply some padding and use a big background image for drawing the corners. The final effect will be the same as of tabs. For example:

#nav li {
 height: 100%;
 padding-left: 1em;
 background: url(tab-left.png) no-repeat 0 0;
 float: left;
}

#nav a {
 float: left;
 height: 100%;
 padding: 0 1em;
 background: url(tab-right.png) no-repeat 100% 0;
}

Remember: the important thing with this technique is padding, not width, so calculate carefully the amount of padding required to get the desired effect.

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.