skip to content

CSS: Tables: border-collapse: collapse

The CSS2 border-collapse property allows you to quickly create formatted tables using plain HTML markup.

Collapsing borders

Here is a sample CSS snippet that contains all you need to format tables with any range of colours, borders and other effects:

<style> table.t1 { margin: 1em 0; border-collapse: collapse; } .t1 tr { border: 1px solid #666; } .t1 th { padding: 2px 4px; background: #ccf; border: 1px dotted; white-space: nowrap; text-align: left; } .t1 td { padding: 2px 4px; border: 1px dotted; background: #ffc; } </style>

Essentially, setting the border-collapse property to collapse allows borders to be applied to TR's and TD's in ways that aren't possible using CSS1.

The styles above have been applied to two tables below. The tables are marked up using nothing fancier than TH for headings and TD for content:

Heading 1Heading 2Heading 3
Heading 1contentcontentcontent
Heading 2contentcontentcontent
Heading 3contentcontentcontent

This is how it should look:

Using the standard TABLE model would require twice as much code, as you'd have to set the background colours, borders and text alignment for each row or cell.

You might want to pay special attention to the section on Border conflict resolution in the W3C specifications. It explains how precedence is determined when borders belonging to different elements overlap.

To summarise, a border that appears 'more solid' will override one that is 'less solid' with the exception of those that are 'hidden'. That explains why, in our example, the solid borders around the rows over-ride the dotted borders around cells.

If your browser renders the above tables differently than the sample provided, it probably isn't following these rules.

Once you've set the border-collapse property of a table to collapse, you can add individual borders to any rows or cells in that table. Here's another demonstration:

1 2 3
4 5 6
7 8 9

You should be seeing a red square inside a yellow one. There will also be a partial green box around the '9', but as it's a 2px border, it is overruled by the other, 3px, borders (see 'border conflict resolution' above).



Post your comment or question