Pretty HTML tables with CSS

Back in old days of web design, making "pretty tables" was usually achieved by nesting one table within another. By setting the background colour of the outer table a few shades darker than the inner one, you could achieve a nice "bordered" look. With the move to XHTML, this is generally considered to be poor design as it contravenes the principle that you should use CSS for the presentation and the HTML only for markup.

So how do you achieve this "pretty table" look using CSS? To anyone who's dabbled in CSS presentation, the answer is obviously by setting the "border" property for each table cell. However, by also setting the "border-collapse" property of the table to "collapse", we get rid of that nasty little gap between the cells, giving us a much nicer look:

KeyValue
ACTAustralian Capital Territory
NSWNew South Wales
NTNorthern Territory
QLDQueensland
SASouth Australia
TASTasmania
VICVictoria
WAWestern Australia

The CSS code you'll need, preferably in a separate file:

table.pretty {
  margin: 1em 1em 1em 2em;
  background: whitesmoke;
  border-collapse: collapse;
}
table.pretty th, table.pretty td {
  border: 1px silver solid;
  padding: 0.2em;
}
table.pretty th {
  background: gainsboro;
  text-align: left;
}
table.pretty caption {
  margin-left: inherit;
  margin-right: inherit;
}

The HTML code is very simple with "pretty" being the only class declaration:

<table class="pretty">
<tr>
<th>Key</th><th>Value</th>
</tr>
<tr>
<td>ACT</td><td>Australian Capital Territory</td>
</tr>
<tr>
<td>NSW</td><td>New South Wales</td>
</tr>
<tr>
<td>NT</td><td>Northern Territory</td>
</tr>
<tr>
<td>QLD</td><td>Queensland</td>
</tr>
<tr>
<td>SA</td><td>South Australia</td>
</tr>
<tr>
<td>TAS</td><td>Tasmania</td>
</tr>
<tr>
<td>VIC</td><td>Victoria</td>
</tr>
<tr>
<td>WA</td><td>Western Australia</td>
</tr>
</table>

Of course, spruce up the colours as much as you like if our monochromatic scheme is a little drab for you.

Due to the large volume of spam, comments are disabled. If you have anything to say, please feel free to contact me directly.

About the author

Ivan's mugshotIvan Lutrov is the owner of Lutrov Interactive. He creates cost effective business websites that are simple, engaging and very easy to use. When not busy working on client and personal projects, he's into photography, fishing, cricket, tennis, music from the 70s, cooking, good wine, and apparently knows "way too much" about movies. He tells it like it is, whether you like it or not. Subscribe to the Lutrov Interactive feed via RSS and follow Ivan on Twitter.