MakeW3web

Rowspan and Colspan

`rowspan` and `colspan` are attributes used in HTML tables to define how many rows or columns a cell should span. These attributes help create complex table structures by merging cells horizontally or vertically. `rowspan` and `colspan` can be applied to both `<th>` (table header) and `<td>` (table data) elements.

  1. `rowspan`: Determines how many rows a cell should span vertically. The default value is 1, which means the cell spans only one row.

Example:

<td rowspan="2">This cell spans two rows</td>
  1. `colspan`: Determines how many columns a cell should span horizontally. The default value is 1, which means the cell spans only one column.

Example:

<td colspan="2">This cell spans two columns</td>

Here's an example of an HTML table that demonstrates the use of `rowspan` and `colspan`:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Rowspan and Colspan Example</title>
    <style>
        table {
            border-collapse: collapse;
            width: 50%;
        }
        th, td {
            border: 1px solid black;
            padding: 8px;
            text-align: center;
        }
        th {
            background-color: #f2f2f2;
            font-weight: bold;
        }
    </style>
</head>
<body>
    <h1>Rowspan and Colspan</h1>
    
    <table>
        <tr>
            <th rowspan="2">Name</th>
            <th colspan="2">Scores</th>
        </tr>
        <tr>
            <th>Math</th>
            <th>English</th>
        </tr>
        <tr>
            <td>Alice</td>
            <td>95</td>
            <td>90</td>
        </tr>
        <tr>
            <td>Bob</td>
            <td>85</td>
            <td>80</td>
        </tr>
    </table>
</body>
</html>

In this example, the "Name" header cell spans two rows, while the "Scores" header cell spans two columns. As a result, the table has a more complex structure with merged cells.

When using `rowspan` and `colspan`, ensure that the table structure is consistent and accessible. Make sure the total number of cells in each row and column is consistent across the entire table. This helps browsers and screen readers interpret the table structure correctly.

Was this page helpful?