๐ŸŽ“ A1Learner
๐Ÿ”

CSS Tables

Table styling sets the borders, spacing and colours of a table and its cells. The border-collapse property joins separate cell borders into single lines.

Borders on every cell

The border shorthand gives the table and every cell a border. With separate borders, each cell keeps its own lines, so shared edges look doubled.

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

Joined borders

The collapse value joins neighbouring cell borders into one line. The cells keep their borders, and the table shares each edge.

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

A styled header row

The header cells take a blue background with white text. Padding gives every data cell more room inside its border.

th {
  background-color: blue;
  color: white;
}
td {
  padding: 8px;
}

Example

table {
  border-collapse: collapse;
}
th, td {
  border: 1px solid black;
  padding: 8px;
}
th {
  background-color: blue;
  color: white;
}
tr:nth-child(even) {
  background-color: lightblue;
}

Key points

  • border-collapse: the property that joins cell borders or keeps them separate
  • Use collapse for one shared line between neighbouring cells
  • A table width behaves like the width of any other block.
  • The text-align property aligns text inside a cell.
  • Padding inside a cell moves the cell content away from its border.
  • A caption titles a table, and CSS can style it like other text.

In this example, the first rule collapses the table borders into single lines. The second rule gives every cell a border and padding. The third rule paints the header cells blue with white text. The last rule paints every even row light blue, and the row for Ana is the even row on this page.

Note

Header cells are bold and centred by default.

Try it Yourself

Edit the code, then press Run.

Runs in your browser โ€” the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.

Exercise

What does border-collapse: collapse do?