Lesson 14 +10 XP

Tables

Tables arrange data in rows and columns, like a spreadsheet on your page.

The basic table

  • <table>: the whole table
  • <tr>: one row
  • <th>: a header cell (bold, at the top)
  • <td>: a normal cell
Code

html
<table>
  <tr>
    <th>Fruit</th>
    <th>Color</th>
  </tr>
  <tr>
    <td>Apple</td>
    <td>Red</td>
  </tr>
  <tr>
    <td>Banana</td>
    <td>Yellow</td>
  </tr>
</table>

Table parts

For big tables, organize them in groups:

  • &lt;caption&gt;: the table's title (goes right after &lt;table&gt;).
  • &lt;thead&gt;: the header rows.
  • &lt;tbody&gt;: the main body rows.
  • &lt;tfoot&gt;: the footer rows (like a total).
Code

html
<table>
  <caption>Weekly sales</caption>
  <thead>
    <tr>
      <th>Day</th>
      <th>Sales</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Mon</td>
      <td>100</td>
    </tr>
  </tbody>
  <tfoot>
    <tr>
      <td>Total</td>
      <td>500</td>
    </tr>
  </tfoot>
</table>

Columns: &lt;colgroup&gt; and &lt;col&gt;

  • &lt;colgroup&gt;: groups columns.
  • &lt;col&gt;: represents one column, so you can style the whole column at once.
Code

html
<table>
  <colgroup>
    <col class="name-col">
    <col class="score-col">
  </colgroup>
  ...
</table>

Spanning: colspan and rowspan

  • colspan=&quot;2&quot;: a cell stretches across 2 columns.
  • rowspan=&quot;2&quot;: a cell stretches across 2 rows.
Code

html
<tr>
  <td colspan="2">This spans two columns!</td>
</tr>

scope for accessibility

On header cells, add scope=&quot;col&quot; or scope=&quot;row&quot; so screen readers know what each header points to.

Code

html
<th scope="col">Fruit</th>
<th scope="row">Apple</th>

TL;DR

  • &lt;table&gt;, &lt;tr&gt;, &lt;th&gt;, &lt;td&gt; = table, row, header cell, data cell.
  • &lt;caption&gt;, &lt;thead&gt;, &lt;tbody&gt;, &lt;tfoot&gt; organize the table.
  • &lt;colgroup&gt;/&lt;col&gt; style whole columns.
  • colspan/rowspan stretch cells.
  • scope helps screen readers.