01 March 2015

Components of an HTML Table

While working with Backbone.js I had to use parent and children views to create various tables. I realized I didn't fully understand how to structure HTML tables so I decided to take a few minutes to do a deep dive on table structure. I want to write this posts to really solidify what I learned and share my knowledge with anyone else who is very curious.

  • The tr tag is a table row
  • The th tag is a table header. This represents the columns in the table
  • The td tag is a unit of table data. td tags are what make up the actual content of the table

Structuring an HTML Table

When setting up an HTML table you should declare all the th cells before listing any td or tr cells. th cells should be listed completely independently of the other tags because they represent the number of columns the HTML table will have and are therefore related to structure and not content.

Filling in Table Content

As far as inputting content in the HTML table, you should create a table row using the tr tag and then fill it with td tags. The td tags represent the content, so within each td tag you should put one element of table data.

The td cells should be nested within the tr cells. This is because a td cell represents an entry, and a tr represents the beginning of a new row. So the overall structure of a tree should look like this

<table>
  <th>First</th>
  <th>Last</th>
  <th>Age</th>

  <tr>
    <td>Jill</td>
    <td>Smith</td>
    <td>50</td>
  </tr>
  <tr>
    <td>Eve</td>
    <td>Jackson</td>
    <td>94</td>
  </tr>
  <tr>
    <td>John</td>
    <td>Doe</td>
    <td>80</td>
  </tr>
</table>

This table will render as:

Obviously, this requires some basic styling. Tables need CSS styling or else the content inside the table will overflow and become disorganized. We can fix this by adding a nice 1px solid black border around the table, th, and td tags.

<style>
  td, th, table {
    border: 1px solid black;
  }
</style>

This causes the table to instead render with a simple border which causes the data to be more organized and readable: