HTML Table

  • Table:
    • <table>
  • Caption:
    • <caption>: must be first child of <table> for accessibility
  • Row Groups:
    • <thead>
    • <tbody
    • <tfoot>
  • Column Groups:
    • <colgroup>
    • <col>
  • Table Row:
    • <tr>
  • Table Cells:
    • <th> (table header cell)
    • <td> (table data cell)

<th> attributes

  • colspan: # of cells you want column to span
  • rowspan: # of cells you want column to span
  • scope: (never use in <td>) specifies if header cell is header for:
    • row, col, rowgroup, colgroup

<td> attributes

  • rowspan, colspan
  • headers: list of space separated strings, each corresponding to id of <th> elements

Basic Example

<style>
  table,
  th,
  td {
    border: 1px solid #dcdcdc;
  }
</style>
<table>
    <caption>Table caption</caption>
    <thead>
      <tr>
        <th scope="col">Trial</th>
        <th scope="col">Starter</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>2hrs/day</td>
        <td>7hrs/day</td>
      </tr>
      <tr>
        <td>5 channels</td>
        <td>32 channels</td>
      </tr>
    </tbody>
    <tfoot>
      <tr>
        <td colspan="2">Footer</td>
      </tr>
    </tfoot>
</table>

Full Example

<html>
  <head>
    <style>
      table {
        border-collapse: collapse;
        overflow: auto;
      }
 
      table,
      th,
      td {
        padding: 3rem;
        border: 1px solid #dcdcdc;
        text-align: center;
      }
    </style>
  </head>
  <body>
    <table>
      <caption>
        Channel Subscriptions
      </caption>
      <colgroup>
        <col span="1" style="background-color: lightblue" />
        <col span="1" style="background-color: lightcyan" />
      </colgroup>
      <thead>
        <tr style="color: white; background-color: lightseagreen">
          <th id="mh-co1" scope="col">Trial</th>
          <th id="mh-co2" scope="col">Starter</th>
        </tr>
        <tr style="color: white; background-color: teal">
          <th id="sh-co2" scope="col">$5.99<br />per month</th>
          <th id="sh-co3" scope="col">$15.99<br />per month</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td headers="mh-co1 sh-co1">2hrs/day</td>
          <td headers="mh-co2 sh-co2">7hrs/day</td>
        </tr>
        <tr>
          <td headers="mh-co1 sh-co1">5 channels</td>
          <td headers="mh-co2 sh-co2">32 channels</td>
        </tr>
      </tbody>
      <tfoot>
        <tr style="color: white; background-color: lightsteelblue">
          <td colspan="2">
            <a href="http://www.example.com" target="_blank">Buy now!</a>
          </td>
        </tr>
      </tfoot>
    </table>
  </body>
</html>