Tip: Adding borders to data tables with CSS

How do you add borders to data tables with CSS? Depending on how you want the borders to display, it can normally be accomplished with three steps.

I constructed a small table and will show it to you as I move through the three steps. I’ll use a medium width, solid style border in the color #00f (blue) for all the border rules. With a width assigned to the entire table, and a border rule added to the table, here’s the beginning CSS.

table {
width: 40em;
border: medium solid #00F;
}

Here’s how that looks (in Firefox).

table with CSS borders appled to table selector

As you can see, applying a border rule to the table selector adds a border to the table only. Step two is to apply the border property to the td and th selectors as well. Here’s the new CSS.

table {
width: 40em;
border: medium solid #00F;
}
th, td {
border: medium solid #00F;
}

This is what you see now.

a table with borders applied to the td and th selectors

You may choose to accept this appearance. But you see that you have some spacing between the table cells between the borders of each data cell. If you don’t like that appearance, the third step will correct it. This step involves the border-collapse property. It is applied to the table selector, like this:

table {
width: 40em;
border: medium solid #00F;
border-collapse:collapse;
}
th, td {
border: medium solid #00F;
}

This rule eliminates the space between cells, but is implemented in a slightly different way in some browsers. Look at the effect in Firefox and Safari.

rendering of border-collapse: collapse in Firefox
Rendering of border-collapse: collapse in Firefox
Rendering of border-collapse: collapse in Safari
Rendering of border-collapse: collapse in Safari

To my eye, there is a thicker border on the top and left in Firefox. (Before you decide that’s unacceptable and write rules to correct it, it would be good to see how other major browsers render the border.)

You can change the border style or width or color, but these three simple steps take care of getting a data table presented with borders.

3 thoughts on “Tip: Adding borders to data tables with CSS”

Leave a Reply