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).
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.
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.
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.
FWIW – I put top and left borders on TABLE – bottom and right borders on table cells…
An interesting solution, David. Still problematic in Firefox but looks the same as above in Safari.
Thanks, its been useful for me.