Style HTML tables with CSS

A brief guide to using tables in CSS

Forms in the past were overused in CSS because they are one of the only ways we can create beautiful page layouts.

Now, with the help of Grid and Flexbox, we can move the table back to what it should do: style sheets.

Let's start with HTML. This is a basic 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>

It is not very attractive by default. The browser provides some standard styles, nothing more:

Of course, we can use CSS to style all the elements of the table.

Let's start with the border. A good border can go a long way.

We can apply it totableElements, and internal elements, such asthwithtd:

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

If we pair it with a certain margin, we get a good result:

A common problem with tables is the ability to add a color in one row and another color in another row. use:nth-child(odd)or:nth-child(even)Selector:

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

This gives us:

If you addborder-collapse: collapse;On the table element, all borders are collapsed into one:

Download mine for freeCSS Manual


More CSS tutorials: