Rounded Corners with CSS and JavaScriptby Simon Willison
Rounded corners are one of the most frequently requested CSS techniques. As with many things in CSS, there are various ways in which this problem can be approached. In this article, I'll look at the pros and cons of some common techniques and introduce a new technique that utilises both CSS and JavaScript.
Before we dive in to the CSS, let's remind ourselves of the old fashioned approach to this problem, which uses layout tables:
<table width="200" cellpadding="0" cellspacing="0">
<tr>
<td width="15"><img src="tl.gif" alt="" /></td>
<td bgcolor="#1b5151"></td>
<td width="15"><img src="tr.gif" alt="" /></td>
</tr>
<tr bgcolor="#1b5151">
<td> </td>
<td>Content goes here</td>
<td> </td>
</tr>
<tr bgcolor="#1b5151">
<td><img src="bl.gif" alt="" /></td>
<td></td>
<td><img src="br.gif" alt="" /></td>
</tr>
</table>
A few years ago this would have been an acceptable solution. Today, it's an ugly hack: that's an awful lot of redundant markup for a relatively unimportant visual decoration. In fact, the above code won't even function as intended in documents served using a strict doctype -- small gaps will appear beneath the corner images, caused by the fact that images are inline elements and, hence, leave space beneath the image for the "tails" on letters such as 'y' and 'j'. The solution, as explained by Eric Meyer in Images, Tables and Mysterious Gaps, is to add the following rule to your stylesheet:
td img { display: block; }
This produces the desired result, as shown here.
But, now we're using CSS hacks to fix ugly table hacks! Let's look at ways to implement the same effect using only CSS.
As a general rule, any decorative image should be implemented as a CSS background image on an existing page element, rather than being dropped in to the page proper using an <img> tag. It's easy to determine whether an image is decorative or contains actual content: ask yourself if the absence of the image would have any effect on the overall content of the page. In the case of rounded corners, the answer is obviously not.
CSS background images are remarkably powerful things. You need only look at the many wonderful designs on display at the CSS Zen Garden for evidence of that. Using CSS, a background image can be applied to any element on a page. Furthermore, it can be repeated horizontally, vertically or not at all; it can be positioned within the background area of the image using absolute measurements, or relative to one of the four corners; it can even be made to stay fixed in place when the element's content scrolls. Unfortunately, CSS 2 imposes one small but significant limitation...