Programación Para Tontos

HTML

Tutorial: your first HTML table to display data

Build a clean HTML table to show data in rows and columns, without using it for page layout.

Years ago people used tables to lay out entire pages. Don't do that. Tables are for one thing: showing tabular data (prices, schedules, grades). Let's do it properly.

Step 1: the basic structure

<table>
  <thead>
    <tr>
      <th>Language</th>
      <th>What it's for</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>HTML</td>
      <td>Structure</td>
    </tr>
    <tr>
      <td>CSS</td>
      <td>Style</td>
    </tr>
    <tr>
      <td>JavaScript</td>
      <td>Interaction</td>
    </tr>
  </tbody>
</table>

<thead> is the header, <tbody> the body, <tr> each row, <th> a header cell, and <td> a regular cell. Yes, a lot of acronyms, no, you don't need to memorize them all today.

Step 2: style it with CSS

table {
  border-collapse: collapse;
  width: 100%;
}

th, td {
  border: 1px solid #333;
  padding: 0.5rem 1rem;
  text-align: left;
}

th {
  background-color: #101e27;
  color: #00e5bf;
}

border-collapse: collapse stops every cell from having its own duplicated border. Without this your table looks like a Windows 95 spreadsheet.

Step 3: add a row with computed data (optional)

<tfoot>
  <tr>
    <td>Total</td>
    <td>3 languages</td>
  </tr>
</tfoot>

<tfoot> is handy for totals or summaries at the bottom of the table.

What did you just learn?

  • The anatomy of a table: table, thead, tbody, tfoot, tr, th, td.
  • How to style it so it doesn't look like it's from the nineties.
  • That tables are for data, not for laying out pages (that's CSS's job).