Combine Table Cells
When you use a table format, sometimes you may want to merge some of the cells vertically or horizontally. In this section, we'll explain how to do it.
Combine table cells horizontally
Use the colspan
attribute to combine table cells horizontally. Set a number of columns to be combined as an attribute value.
For example, to combine the first two cells of the second row like shown in the illustration below, add colspan="2"
as the attribute value of the first <td>
element under the second <tr>
element.
Combine table cells vertically
Use rowspan
attribute to combine table cells vertically. Set a number of rows to be combined as an attribute value.
For example, to combine the cells in the second and third row of the first column like shown in the illustration below, add rowspan="2"
as the attribute value of the first <td>
element under the second <tr>
element.
Practice
Objective:
Merge table cells in HTML
1. Add code to create a table in the HTML file
- Open chapter5.html with VS Code
- Add the following code before the
<style>
tag created in the previous practice
<h3>2. Merge cells horizontally</h3>
<table>
<tr>
<th>header</th>
<th>header</th>
<th>header</th>
</tr>
<tr>
<td colspan="2">item</td>
<td>item</td>
</tr>
<tr>
<td>item</td>
<td>item</td>
<td>item</td>
</tr>
</table>
<h3>3. Merge cells vertically</h3>
<table>
<tr>
<th>header</th>
<th>header</th>
<th>header</th>
</tr>
<tr>
<td rowspan="2">item</td>
<td>item</td>
<td>item</td>
</tr>
<tr>
<td>item</td>
<td>item</td>
</tr>
</table>
After editing the file, make sure that you save it (⌘ + S for Mac, Ctrl + S for Windows).
2. Check the result with a browser
- Open chapter5.html with a browser
- You'll see tables with merged cells like those below
You can also check the sample result here (Demo Site).