CSS3 tables with rounded corners and css selectors

css3 table with rounded cornersI recently had to style a table for a shopping cart with rounded corners and a drop shadow. So how is this done? It would be great if you could just slap “border-radius: x” straight on to the <table> element and it would be done but unfortunately this doesn’t work. You have to get a rounded corner on to each <th> or <td> at the corners of the table.

So how do you do that? Add a class to each corner cell? I suppose you could but it would mean ugly html. CSS to the rescue! By using child selectors you can get those round corners in there without touching the html at all…

For example: to target the top left-hand cell (assuming you have a header on your table), you target th:first-child (the first <th> element); likewise to get the top right-hand cell you target th:last-child.

To get the bottom left-hand cell you need to target the first cell of the last row of the table. In this case, your selector will be: tr:last-child td:first-child

…and for the final corner: tr:last-child td:last-child

Finally, the zebra striping on the table is done using the :nth-child selector: tr:nth-child(even) will select only the even numbered rows (note: in the following example I have used tr:nth-child(even) td as I am using gradients (the gradients need to be on the <td> element else they stick out of the rounded corner in Firefox).

Here’s a live example of my CSS3 tables with rounded corners on dabblet.com

The html markup for the table was generated using my own Create Table plugin for Coda.