Styling Tables Using CSS

You can create a table with borders or without borders. By default, browsers display table without borders.

images/articles/css/css24.webp

To add borders to all the cells

th, td {
border: 1px solid black;
}

By default, browsers add a little space between cells. This creates gaps between the hairline borders. If you don't want these gaps, add a specification for the table:

table {
border-collapse: collapse;
}

By default, browsers don't add breathing room between the table cell borders and the text they contain. The solution is to add padding.

th, td {
border: 1px solid black;
padding: .25em;
}

By default, browsers adjust cell size to contents. Instead of letting the browser allocate space on the basis of need, you can style the cells for custom width by using width. You can also control the vertical alignment within cells.

Space Between Table Cells

CSS has the border-spacing property, which sets an equal amount of space between data cells' top, bottom, left, and right sides. For example,

border-spacing: 8px;

Empty Table Cells

If a table data cell has no data (not even spaces or non-breaking spaces), it simply appears as a blank box at the default width and height of the column and row. The empty-cells property allows you to specify how that empty data cell (and its border) is presented.

show will force the empty data cell to display its background and border.

hide will leave a visual gap in place of the data cell.

Position of Table Caption

The <caption> tag lets you embed identifying text in a table. You can set the align attribute in the tag to define where the caption should appear in relation to the table, but this is being deprecated in favor of the CSS caption-side property, which does the same thing.

table {
table-layout: auto;
border-spacing: 8px;
border-collapse: separate;
empty-cells: hide;
caption-side: bottom;
width: 75%;
margin: 40px auto;
}