First, let's create a basic HTML table with a few rows and columns. Use the following code to create a table with 4 rows and 3 columns:
<table border="1">
<tr>
<td>Cell 1</td>
<td>Cell 2</td>
<td>Cell 3</td>
</tr>
<tr>
<td>Cell 4</td>
<td>Cell 5</td>
<td>Cell 6</td>
</tr>
<tr>
<td>Cell 7</td>
<td>Cell 8</td>
<td>Cell 9</td>
</tr>
<tr>
<td>Cell 10</td>
<td>Cell 11</td>
<td>Cell 12</td>
</tr>
</table>Now, let's add this code to the embedded playground below:
A table header is a row at the top of a table that contains labels for each column. It helps users understand the data in the table by providing context. In HTML, table headers are created using the <th> element, which stands for 'table header'. Now, let's add a header row to our table. Add the header code above the rows:
<tr>
<th>Header 1</th>
<th>Header 2</th>
<th>Header 3</th>
</tr>In this step, we will use the rowspan attribute to merge cells vertically. A rowspan lets a table cell stretch vertically across multiple rows. Imagine one long box covering several smaller ones stacked on top of each other.
Update the first cell of the second row (Cell 4) with the following code and also delete the first cell of the third row (Cell 7):
<td rowspan="2">Cell 4</td>
So the code should look like this:
<table border="1">
<tr>
<th>Header 1</th>
<th>Header 2</th>
<th>Header 3</th>
</tr>
<tr>
<td>Cell 1</td>
<td>Cell 2</td>
<td>Cell 3</td>
</tr>
<tr>
<td rowspan="2">Cell 4</td>
<td>Cell 5</td>
<td>Cell 6</td>
</tr>
<tr>
<td>Cell 8</td>
<td>Cell 9</td>
</tr>
<tr>
<td>Cell 10</td>
<td>Cell 11</td>
<td>Cell 12</td>
</tr>
</table>
When you run the code, notice how Cell 4 now spans two rows, merging with Cell 7.
Next, we will use the colspan attribute to merge cells horizontally. A colspan lets a table cell stretch horizontally across multiple columns. Picture one wide box covering several smaller ones side by side.
Update the first cell of the first row (Cell 1) with the following code and also delete the second cell of the first row (Cell 2):
<td colspan="2">Cell 1</td>
So the code should look like this:
<table border="1">
<tr>
<th>Header 1</th>
<th>Header 2</th>
<th>Header 3</th>
</tr>
<tr>
<td colspan="2">Cell 1</td>
<td>Cell 3</td>
</tr>
<tr>
<td rowspan="2">Cell 4</td>
<td>Cell 5</td>
<td>Cell 6</td>
</tr>
<tr>
<td>Cell 8</td>
<td>Cell 9</td>
</tr>
<tr>
<td>Cell 10</td>
<td>Cell 11</td>
<td>Cell 12</td>
</tr>
</table>
When you run the code, notice how Cell 4 now spans two rows, merging with Cell 7.
You're previewing this lesson. Get full access to this lesson and hundreds more — each one ready to teach, with interactive activities, printable resources and pupil progress tracking built in.