s

Using a background image on a table row

Nov 26, 2006

How many times have you had the need to apply a background image to a table row? Chances are, not very often. Before a week or two ago, I'd never even thought about it. I was living in blissful ignorance of the problems that can occur when trying to achieve this. But, of course, things don't go perfectly forever. Recently, Buck handed me a design for a client that incorporated complicated styling for a table that presented information. After the requisite belly-aching, I did what was asked of me. Very simple CSS:

tr.bar { background: url(/images/tr_background.gif) no-repeat 0 0; }

As you'd probably guess, it works perfectly in Firefox, but not Internet Explorer. But surprisingly, it doesn't work in Safari either. So, there must be more to this than just IE and their non-compliance. Having moved on to another project, I didn't have time to research the bug or find a solution. So, I handed it off to Colin, who, after a little experimentation, was able to find an excellent workaround.

The problem with IE and Safari is that they don't allow a background image to be applied to a <tr>. What do they do when you try this? The <td>'s inherit the background. This might not be a huge problem normally, but the reason the <tr> needed the background to begin with is because it had rounded corners on the top-right and top-left. So with the bug, each <td> had a rounded corner on the top-left, which looked a little funny.

Colin found a fix for this, which entailed making a class for the first and last <td>'s and having a separate image for them than the center <td>'s. This would work, but why not use the same image? Colin used the idea of having a class for the first and last <td>, but instead of making new images, he just fiddled with the background-position.

Here's what he came up with:

td.first { background: url(/images/tr_background.gif) no-repeat 0 0; }
td { background: url(/images/tr_background.gif) no-repeat 50% 0; }
td.last { background: url(/images/tr_background.gif) no-repeat 100% 0; }

This way, we use the same image. The first <td> starts the image in the top-right, showing the rounded corner, the middle <td>'s center the image, so you don't see either corner, and the last <td> starts the image in the top-left so you can again see the intended rounded corner. Perfect.

Tagged: xhtmlcss