HTML Tables
This lesson is part of the Web Programming 1 Course.
To add a table to a page add a table element, and then add two child elements to it. The first child should be a thead element, and the second child should be a tbody element.
<table border="1">
<thead>
</thead>
<tbody>
</tbody>
</table>
The thead element will contain the column headers for our table, while the tbody element will contain rows that display the data.
Note that a border attribute has been added to the table element, which will add a 1 pixel border around every cell in the table. There are better ways of adding borders to your tables, but we'll have to wait until we get to CSS to learn about them.
We'll add column headers later, so for now we'll leave the thead element empty while we work on adding rows to the tbody element.
To add a row to the body of the table, start by adding a tr element as a child of the tbody element, then add 5 td elements as children of the tr. Your table will look like this:
<table border="1">
<thead>
</thead>
<tbody>
<tr>
<td>2022</td>
<td>x</td>
<td>x</td>
<td>x</td>
<td>x</td>
</tr>
</tbody>
</table>
In the video, we added a few more rows the the tbody element, but to keep things simple here, we'll leave just one row in the body of the table.
Now we'll add column headers by adding a row inside the thead element. But instead of using td elements inside this row, we'll use th elements, like so:
<table border="1">
<thead>
<tr>
<th>Year</th>
<th>Q1</th>
<th>Q2</th>
<th>Q3</th>
<th>Q4</th>
</tr>
</thead>
<tbody>
<tr>
<td>2022</td>
<td>x</td>
<td>x</td>
<td>x</td>
<td>x</td>
</tr>
</tbody>
</table>
The difference between th and td elements is that th elements will center their content and display it as bold text.
Finally, we'll add a header row (to the thead element) that will display the title of the table. Add a row as the first child of the thead but put just one th element that has a colspan attribute with a value of 5, like so:
<table border="1">
<thead>
<tr>
<th colspan="5"><h3>Sales Report</h3></th>
</tr>
<tr>
<th>Year</th>
<th>Q1</th>
<th>Q2</th>
<th>Q3</th>
<th>Q4</th>
</tr>
</thead>
<tbody>
<tr>
<td>2022</td>
<td>x</td>
<td>x</td>
<td>x</td>
<td>x</td>
</tr>
</tbody>
</table>
We've only added one cell to this row (a single th element), but by setting the colspan attribute to a value of 5, the cell will span across 5 columns.
You could make a cell span across multiple rows too, by adding a rowspan attribute, but we won't be messing around with that now (the tables worksheet has a bonus problem on rowspan if you are up for that challenge).
Our table doesn't look great now, but later when we get into CSS we can learn how to make it look much better.