Learn how to style HTML tables using CSS.

In the past, tables were often misused for page layout purposes. However, with the introduction of Grid and Flexbox in CSS, tables can now be used specifically for styling tabular data.

To start, let’s look at a basic HTML table:

<table>
  <thead>
    <tr>
      <th scope="col">Name</th>
      <th scope="col">Age</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th scope="row">Flavio</th>
      <td>36</td>
    </tr>
    <tr>
      <th scope="row">Roger</th>
      <td>7</td>
    </tr>
  </tbody>
</table>

By default, tables have a plain appearance, with the browser applying some default styles:

Default Table Styling

To style the table and its elements, we can use CSS.

To add a border, we can target the table, th, and td elements and set the border property:

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

When combined with some margin, this creates a more visually appealing table:

Styled Table with Border

Another common requirement is to apply different background colors to alternating rows. This can be achieved using the :nth-child(odd) and :nth-child(even) selectors:

tbody tr:nth-child(odd) {
  background-color: #af47ff;
}

This results in a visually distinct table:

Styled Table with Alternate Row Colors

Moreover, by adding the border-collapse: collapse; property to the table element, all borders will collapse into a single line:

Styled Table with Collapsed Borders

By applying these CSS techniques, you can easily style your HTML tables to match the look and feel of your website.