0
0
HtmlHow-ToBeginner · 3 min read

How to Merge Cells in HTML Table: Simple Guide

To merge cells in an HTML table, use the colspan attribute to combine cells horizontally and the rowspan attribute to combine cells vertically. Add these attributes to the <td> or <th> elements with a number indicating how many cells to merge.
📐

Syntax

The colspan attribute merges cells horizontally across columns, while rowspan merges cells vertically across rows. Both are added inside a <td> or <th> tag with a number value.

  • colspan="n": merges n columns into one cell.
  • rowspan="n": merges n rows into one cell.
html
<td colspan="2">Merged horizontally</td>
<td rowspan="3">Merged vertically</td>
💻

Example

This example shows a table where the first row merges two columns using colspan, and the first cell in the second row merges three rows using rowspan.

html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Merge Cells Example</title>
  <style>
    table { border-collapse: collapse; width: 50%; }
    th, td { border: 1px solid #333; padding: 0.5rem; text-align: center; }
  </style>
</head>
<body>
  <table>
    <tr>
      <th colspan="2">Header merged across 2 columns</th>
      <th>Header 3</th>
    </tr>
    <tr>
      <td rowspan="3">Rowspan 3 rows</td>
      <td>Cell 2</td>
      <td>Cell 3</td>
    </tr>
    <tr>
      <td>Cell 4</td>
      <td>Cell 5</td>
    </tr>
    <tr>
      <td>Cell 6</td>
      <td>Cell 7</td>
    </tr>
  </table>
</body>
</html>
Output
A table with a top header cell spanning two columns, and a left cell in the second row spanning three rows vertically.
⚠️

Common Pitfalls

Common mistakes when merging cells include:

  • Not adjusting the number of cells in other rows to match merged cells, causing layout issues.
  • Using colspan or rowspan values that are too large, breaking the table structure.
  • Forgetting that merged cells reduce the number of cells needed in that row or column.

Always count carefully how many cells remain after merging to keep the table balanced.

html
<!-- Wrong: colspan too large, breaks layout -->
<tr>
  <td colspan="5">Too wide</td>
  <td>Extra cell</td> <!-- This cell causes layout issues -->
</tr>

<!-- Right: colspan matches remaining cells -->
<tr>
  <td colspan="4">Correct width</td>
</tr>
📊

Quick Reference

AttributePurposeExample
colspanMerge cells horizontally across columnsMerged 3 columns
rowspanMerge cells vertically across rowsMerged 2 rows

Key Takeaways

Use colspan to merge cells horizontally and rowspan to merge cells vertically.
Add these attributes inside <td> or <th> tags with the number of cells to merge.
Ensure the total number of cells in each row matches after merging to avoid layout problems.
Test your table in a browser to confirm merged cells display as expected.
Keep your table structure balanced by adjusting other cells when using merged cells.