Skip to content

CSS Tables

The HTML <table> element is ideal for displaying structured data. CSS provides a range of properties to control the appearance of tables, making them more readable and attractive.

border

Adding borders to a table is the most basic and important styling step. You can add borders to table, th (table header cell), and td (table data cell).

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

By default, table borders are separated, meaning each cell has its own border, which leads to a double-border look.

border-collapse

The border-collapse property is used to control whether table borders are collapsed into a single border or separated.

  • collapse: Collapses adjacent borders into a single border. This is the most common setting and makes the table look cleaner.
  • separate: (Default) Borders are separated.
css
table {
  border-collapse: collapse;
  width: 100%; /* Make the table width fill its container */
}

th, td {
  border: 1px solid #ddd;
  padding: 8px; /* Add padding to let content breathe */
}

text-align and vertical-align

  • text-align controls the horizontal alignment of content within cells (left, right, center).
  • vertical-align controls the vertical alignment of content within cells (top, middle, bottom).

By default, <th> content is centered and bold, while <td> content is left-aligned.

css
th {
  text-align: left;
  background-color: #f2f2f2;
}

td {
  vertical-align: middle;
}

padding

Adding padding to th and td is very important; it prevents content from sticking to the borders, greatly improving readability.

css
th, td {
  padding: 15px;
}

Zebra Stripes

Adding alternating background colors to table rows (i.e., "zebra stripes") can help users track data horizontally more easily. This can be achieved using the :nth-child() pseudo-class.

  • :nth-child(even): Selects even rows of <tr> elements.
  • :nth-child(odd): Selects odd rows of <tr> elements.
css
tr:nth-child(even) {
  background-color: #f2f2f2;
}

Hover Highlight

Changing the background color of a row when the mouse hovers over it can provide clear visual feedback to the user.

css
tr:hover {
  background-color: #ddd;
}

Responsive Tables

On small screen devices, wide tables may overflow the screen, causing horizontal scrollbars, which is a poor user experience.

A simple responsive solution is to set the table container to overflow-x: auto. This way, only the table itself scrolls horizontally without breaking the entire page layout.

html
<div style="overflow-x:auto;">
  <table>
    ...
  </table>
</div>

By combining these CSS properties, you can transform a raw HTML table into a clear, beautiful, and easy-to-use data presentation tool.

Content is for learning and research only.