Lesson 53 +10 XP

Advanced Tables

Advanced Tables

You already know the basics. Now let's make tables beautiful and powerful!

Table borders

By default, tables have no visible borders. Add them with CSS:

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

border-collapse: collapse makes the double borders become one clean border.

Table sizes

Set the width of a table, and the height of rows:

table {
  width: 100%;
}
th {
  height: 50px;
}

Column widths

th, td {
  width: 25%;
}

Padding and spacing

  • padding: space INSIDE cells.
  • border-spacing: space BETWEEN cells (when borders aren't collapsed).
th, td {
  padding: 15px;
}

Header styling

Style the header row with a background color:

th {
  background-color: #04AA6D;
  color: white;
}

Zebra stripes

Color alternate rows so they're easy to read:

tr:nth-child(even) {
  background-color: #f2f2f2;
}

Hover highlight

Light up a row when the mouse hovers over it:

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

Colgroup: style whole columns

Use <colgroup> and <col> to style a whole column at once:

<table>
  <colgroup>
    <col span="2" style="background-color: lightblue;">
    <col style="background-color: lightgreen;">
  </colgroup>
  <tr>
    <th>Name</th>
    <th>Score</th>
    <th>Grade</th>
  </tr>
</table>

span="2" means "apply this style to 2 columns."

A full fancy table

<style>
  table { border-collapse: collapse; width: 100%; }
  th, td { border: 1px solid #ddd; padding: 12px; text-align: left; }
  tr:nth-child(even) { background-color: #f2f2f2; }
  th { background-color: #04AA6D; color: white; }
</style>

<table>
  <tr>
    <th>Name</th>
    <th>City</th>
    <th>Score</th>
  </tr>
  <tr>
    <td>Ada</td>
    <td>London</td>
    <td>95</td>
  </tr>
  <tr>
    <td>Linus</td>
    <td>Helsinki</td>
    <td>88</td>
  </tr>
</table>

TL;DR

  • Borders: border + border-collapse: collapse.
  • Size: width on the table, height on rows.
  • Space: padding inside cells.
  • Zebra stripes: tr:nth-child(even).
  • Hover: tr:hover.
  • <colgroup>/<col> style whole columns.