Styling Table Cells with CSS

Standard HTML tables are functional but not very interesting to look at. But we can use CSS to adjust every aspect of these tables to make them appear just how we want, and to make them fit with the style of our website.

Note that before we can style tables we need to ensure that each table has the property border="1". Otherwise the table will display no borders by default, so any changes we make to the border styling will be invisible.

Let's take a look at a typical table:

Company accounts
Year Income Expenditure Profit
2004 10m 8m 2m
2005 13m 10m 3m
2006 16m 12m 4m

Here we have a typical HTML table layout four columns and four rows, with table headings at the top of each column and a caption to tell the user what the table is showing. Now let's see how we can use CSS to make it look a lot more attractive.

Controlling table cell widths

The column widths in the above table are all sized to fit the width of the data contained within that column. This leads to an uneven and untidy appearance to the table. So let's begin by making all of our columns the same width. Because our columns will stay the same width all the way down, we can apply a width property to any of the cells within a column. In this case we will apply it to the table heading <th> tag, and this will set the width of any column with a heading, which in our case is all columns:

th {
	width: 7em;
}

We can see that this has had a dramatic effect on our table appearance:

Company accounts
Year Income Expenditure Profit
2004 10m 8m 2m
2005 13m 10m 3m
2006 16m 12m 4m

There, doesn't that look much nicer? When specifying table column widths it is a good idea to use the same units that you have used to specify the text size of the table cell data. In other words, if you have specified text size in ems, it is best to specify cell widths also in ems rather than pixels.