The colspan attribute in HTML is used in table cells (<td> or <th>) to span a cell across multiple columns. It helps in merging columns to create flexible table layouts.
- Specifies the number of columns a cell should span.
- Accepts a positive integer value (default is 1).
- Used to merge cells horizontally in a table.
Note: colspan="0" spans all remaining columns, but is not reliably supported in HTML5; use a positive integer value instead.
Syntax
<td colspan = "value">table content...</td>- Can be used with <td> and <th> elements.
- Specifies how many columns a cell spans.
- Value should be a positive integer.
Attribute Values
- number: Specifies how many columns a cell spans. Use a positive integer; colspan="0" spans remaining columns but is not reliably supported.
Using with <td> tag
The colspan attribute, when used with the <td> tag, specifies the number of columns a table cell should span.
Syntax
<td colspan="value">Table content...</td>- The value defines how many columns the cell spans.
- The value must be a positive integer.
Example: Implementation of colspan attribute with td attribute with an example.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, initial-scale=1.0">
<title>HTML colspan Attribute</title>
<style>
table,
th,
td {
border: 1px solid black;
border-collapse: collapse;
padding: 6px;
text-align: center;
}
</style>
</head>
<body>
<center>
<h6>The HTML colspan Attribute</h6>
<table>
<tr>
<th>Name</th>
<th>Expense</th>
</tr>
<tr>
<td>Arun</td>
<td>$10</td>
</tr>
<tr>
<td>Priya</td>
<td>$8</td>
</tr>
<!-- The last row -->
<tr>
<!-- This td will span two columns, that is a
single column will take up the space of 2 -->
<td colspan="2">Sum: $18</td>
</tr>
</table>
</center>
</body>
</html>
Using with <th> tag
The colspan attribute, when used with the <th> tag, specifies the number of columns a header cell should span.
Syntax:
<th colspan="value">Table content...</th>- The value defines how many columns the header cell spans.
- The value must be a positive integer.
Example: The implementation of rowspan attribute with th attribute with an example.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, initial-scale=1.0">
<title>HTML colspan Attribute</title>
<style>
table,
th,
td {
border: 1px solid black;
border-collapse: collapse;
padding: 6px;
text-align: center;
}
</style>
</head>
<body>
<center>
<h6>HTML colspan Attribute</h6>
<table>
<tr>
<th colspan="2">Expense</th>
</tr>
<tr>
<td>Arun</td>
<td>$10</td>
</tr>
<tr>
<td>Priya</td>
<td>$8</td>
</tr>
</table>
</center>
</body>
</html>