The colspan attribute
The colspan attribute controls the spanning of columns in an HTML table. It applies to the th and td tags.
Accepted value: integer starting from 1.
How to use: add this attribute to any cell td or th. If, for example, you set colspan to 2, then the cell to which you set this will occupy two columns of the table. At the same time, the neighboring cells on the right will not go anywhere, our expanded cell will displace them and the table will fall apart. To prevent this from happening, you need to delete one of the cells on the right. See the examples for a better understanding.
Example . Table without joins
Let's look at the table without joins that we'll be working with next:
<table>
<tr>
<td>cell1</td>
<td>cell2</td>
<td>cell3</td>
</tr>
<tr>
<td>cell4</td>
<td>cell5</td>
<td>cell6</td>
</tr>
<tr>
<td>cell7</td>
<td>cell8</td>
<td>cell9</td>
</tr>
</table>
table, td, th {
border: 1px solid black;
}
:
Example . Let's expand the cell into two columns
Let's try to expand the 1 cell across two columns by giving it a colspan attribute of 2. This will push out the cells on the right and the table will fall apart:
<table>
<tr>
<td colspan="2">cell1</td>
<td>cell2</td>
<td>cell3</td>
</tr>
<tr>
<td>cell4</td>
<td>cell5</td>
<td>cell6</td>
</tr>
<tr>
<td>cell7</td>
<td>cell8</td>
<td>cell9</td>
</tr>
</table>
table, td, th {
border: 1px solid black;
}
:
Example . Let's expand the cell without breaking the table
Now let's try to fix the problem with the table falling apart from the previous example, let's delete one of the cells to the right of ours (this is cell 2 or 3 - it doesn't matter):
<table>
<tr>
<td colspan="2">cell1</td>
<td>cell2</td>
</tr>
<tr>
<td>cell4</td>
<td>cell5</td>
<td>cell6</td>
</tr>
<tr>
<td>cell7</td>
<td>cell8</td>
<td>cell9</td>
</tr>
</table>
table, td, th {
border: 1px solid black;
}
:
Example . Let's expand the cell into three columns
Let's expand the 1 cell by 3 columns and give it a colspan attribute of 3. Let's also remove one more cell on the right so the table doesn't fall apart:
<table>
<tr>
<td colspan="3">cell1</td>
</tr>
<tr>
<td>cell4</td>
<td>cell5</td>
<td>cell6</td>
</tr>
<tr>
<td>cell7</td>
<td>cell8</td>
<td>cell9</td>
</tr>
</table>
table, td, th {
border: 1px solid black;
}
:
Example . Colspan and rowspan at the same time
Let's try to merge cells with numbers 4, 5, 7 and 8 using the attributes colspan and rowspan (we will remove the previous merges from the table):
<table>
<tr>
<td colspan="3">cell1</td>
</tr>
<tr>
<td colspan="2" rowspan="2">cell4</td>
<td>cell6</td>
</tr>
<tr>
<td>cell9</td>
</tr>
</table>
table, td, th {
border: 1px solid black;
}
:
See also
-
attribute
rowspan,
which combines the rows of a table