The Latest...

Using CSS to style tables

Posted: June 13, 2009 in Web Design

Ok, I haven't made any tech geeky posts in a while, so I thought I'd go ahead and throw this in. If nothing else, it'll give me an easy place to find it when I forget it myself.

Even though using tables for web page layout is pretty much considered a no-no these days, we still need tables when presenting tabular data. The problem is, if you're using an XHTML strict doctype, attributes like border="1" are no longer valid mark-up. So, how do we handle tables in CSS? Here's a quick reference list to most of the common table attributes.

cellpadding="0"td { padding: 0;}
cellspacing="1"table { border-spacing: 1px; }
border="1"td { border: 1px solid #000; }
valign="top"td { vertical-align: top; }
align="right"td { text-align: right; }

So this:

<table cellpadding="5" cellspacing="0" border="1" width="600">
<td align="center" valign="top">

Can be be written as:


With the following CSS:

table { border-spacing: 0; width: 600px; }
td { padding: 5px; text-align: center; vertical-align: top; }

Other useful tidbits:

border-collapse (collapse|separate|inherit): When using the border property on both the table and the td, you'll get a double border between cells. Use border-collapse to compress it into a single border.

empty-cells (show|hide|inherit): Specifies whether to show empty cells or not. No more non-breaking spaces required!

Also remember that you can set top, bottom, left, and right padding to different values.There are advantages to using CSS over the old method.

  • Different padding values for all sides of the cell.
    With cellpadding you can only have a single value, but with CSS, you can have different values for each side.
  • Different border thicknesses
    With the old border= method, you had a single value. CSS borders can not only be thinner, but they can be dashed, dotted, or a number of different things. Plus, you can have different borders for each side, or no border for some sides. And the table itself can have a different border than the cells.
  • Table margins
    You can also use CSS to add margins around the outside of your table. This is not possible with attributes at all. If you have two tables on top of each other, you would normally need to use a space between them to separate them. With CSS, you don't.

The sky is pretty much the limit when using CSS. Experiment and see what you can come up with.

Add Comment

Click to reload a new image.

< Back to blog