Styling tables

HTML tables by default are rough to the eye, fortunately CSS can help us change this...

Controlling width and styling borders

One of the easiest changes we can make to a table is to alter its borders and give it a set size:

Item Quantity Cost
Total £4.70
6 pack apples 1 £1.70
Chocolate Orange 3 £1.00
  • Table width has been set to 100% of its container
  • Overflow has been set to auto to enable a scrollbar on horizontal overflow
  • Table headers in the thead have been given a solid bottom border
  • Table data cells in the tbody have been given bottom and right dashed borders
  • The last table data cells for each row in the tbody have had their right border removed
  • The th in the tfoot has been given a dashed right border
  • Text has been aligned to the right of the columns

Applying all of that styling is a bit verbose though, fortunately we have a border-collapse property which can be used to prevent double borders occuring. Here is an example of double borders:

Item Quantity Cost
Total £4.70
6 pack apples 1 £1.70
Chocolate Orange 3 £1.00

Applying border-collapse: collapse will resolve the double-border issue:

Item Quantity Cost
Total £4.70
6 pack apples 1 £1.70
Chocolate Orange 3 £1.00

If you like the double borders, you can control the size of the gap between borders as long as border-collapse: collapse is not set:

Item Quantity Cost
Total £4.70
6 pack apples 1 £1.70
Chocolate Orange 3 £1.00

Styling the contents of a table

Often, we will want the header of a table to be a different colour from the body. We might also want a banded effect where every other row is highlighted a different colour. This can easily be done with usage of psuedo-class selectors:

Applying border-collapse: collapse will resolve the double-border issue:

Item Quantity Cost
Total £4.70
6 pack apples 1 £1.70
Chocolate Orange 3 £1.00
  • Table headers have a light blue colour
  • Every even table row inside the table body is a light pink
  • Hovering over a table row changes the background colour and produces a box shadow

If we want to style columns, we must make use of the colgroup and col elements:

Item Quantity Cost
Total £4.70
6 pack apples 1 £1.70
Chocolate Orange 3 £1.00

This example styles the last column to have a light gray background colour.

It is important when using the colgroup element that it comes after any caption and before any thead, tbody, tfoot and tr elements.