Styling Tables with CSS
By default, HTML tables look very plain. But it doesn't have to be that way. You can use CSS to add borders, spacing, and colors to make your data much easier to read.
A well-styled table helps users scan across rows and down columns without getting lost. To do this effectively, it's often helpful to group your rows using the thead (table head) and tbody (table body) tags, which give you specific hooks for your CSS.
Adding Borders
To add borders to your table cells, you can use the CSS border property:
Notice that we added a border for both the table header cells (th) and the table data cells (td). If your table doesn't have any header cells, you can simply omit the th selector.
We could also have provided a border for the table itself, but that's not necessary if we're providing borders for the cells. Besides, if we did, we'd end up with double borders.
Collapsing Borders
If you simply add a border to a table and its cells, you'll end up with a double-line effect (due to the borders of adjacent cells). To fix this and create clean, single-line boundaries, use the CSS border-collapse property:
Notice that this is applied to the table element, not the th and td elements.
Adding Space with Padding
Data that touches the edges of a cell is hard to read. You should always add some padding to your th and td elements to let the text breathe.
Full Working Example
In the following example, we combine border-collapse, padding, and background-color to create a modern, styled table. Notice how we target the row inside the thead differently from the rows in the tbody:
Tip: Hover Effects
To help users keep their place in a large table, you can add a hover effect to the rows in the table body. You can do this by using the CSS :hover pseudo-class like this: tbody tr:hover { background-color: #f5f5f5; }.