What does the colspan attribute do?
The colspan attribute in HTML is used on <td> or <th> tags to merge several table columns into one cell.
In other words, it defines how many columns a given cell should span.
Main purpose
When a table needs one cell that spans several adjacent columns, colspan is used.
Example:
html
<table border="1">
<tr>
<th>Item</th>
<th>Quantity</th>
<th>Price</th>
</tr>
<tr>
<td colspan="2">Bread (2 loaves)</td>
<td>$80</td>
</tr>
</table>Here the cell with the text "Bread (2 loaves)" merges two columns: "Item" and "Quantity".
Example with a numeric value:
html
<td colspan="3">Total: $1500</td>This cell will merge three columns into one wide cell.
It can also be used in headers:
html
<th colspan="2">Contact information</th>Important:
- The
colspanvalue is an integer (for example,colspan="2"). - The default value is 1 (the cell occupies only one column).
- Specifying the wrong value can make the table "shift" - breaking the alignment of the columns.
Difference from rowspan:
| Attribute | What it does | Direction |
|---|---|---|
colspan | Merges columns | Horizontal |
rowspan | Merges rows | Vertical |
Conclusion:
The colspan attribute merges several columns in a table, allowing you to create one wide cell.
It is used for total rows, headers, or any case where data spans several columns.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.