Merging Cells in HTML Tables

Merging Cells in HTML Tables

Introduction

Sometimes, it is necessary to merge cells in HTML tables to create a more complex structure or to span data across multiple cells.

Rowspan attribute
The rowspan attribute allows you to merge cells vertically. By specifying a value for rowspan, you can indicate how many rows a cell should span.
Colspan attribute
The colspan attribute, on the other hand, enables you to merge cells horizontally. It specifies the number of columns a cell should span.

To merge cells, you need to identify the appropriate <td> or <th> element and add the rowspan or colspan attribute with the desired value.

Here's an example of merged cells:

                
Month Savings
January February
$100 $150 $250
$200 $300

In the above example, the first row has two merged cells using colspan, and the second row has one merged cell using rowspan.


 Merging Cells in HTML Tables
  

  
Merged Cell 1 Merged Cell 2
Cell 1 Cell 2 Cell 3
Cell 4 Cell 5 Cell 6

  Merging Cells in HTML Tables
  
  
Merged Cell 1 Merged Cell 2
Cell 1 Cell 2 Cell 3
Cell 4 Cell 5 Cell 6

In this code, two buttons have been added below the table: "Merge Rows" and "Merge Columns." Clicking on these buttons triggers the JavaScript functions mergeRows() and mergeColumns() respectively.

The mergeRows() function merges all the cells in each row to have the same row span as the first cell in the first row, achieving vertical merging of rows.

The mergeColumns() function merges all the cells in each row into the first cell of that row by increasing its column span. It removes the extra cells and expands the first cell to span across the columns, achieving horizontal merging of columns.

         
  Merging Cells in HTML Tables
  
  
Merged Cell 1 Merged Cell 2
Cell 1 Cell 2 Cell 3
Cell 4 Cell 5 Cell 6