askvity

How to Merge Cells in HTML?

Published in HTML Tables 2 mins read

You can merge cells in HTML tables using the rowspan and colspan attributes. These attributes allow you to create cells that span across multiple rows or columns.

Merging Rows with rowspan

The rowspan attribute is used to merge cells vertically, creating a single cell that occupies the space of multiple rows.

How it Works:

  • You add the rowspan attribute to the <td> or <th> tag of the first cell you want to merge.
  • The value of rowspan specifies the number of rows that the cell should span.
  • The cells in the rows below the first cell that you would like to be merged will be automatically shifted to the right.

Example:

<table border="1">
  <tr>
    <th rowspan="2">Name</th>
    <th>Age</th>
    <th>City</th>
  </tr>
  <tr>
    <td>25</td>
     <td>New York</td>
  </tr>
  <tr>
     <td>John Doe</td>
     <td>30</td>
      <td>London</td>
    </tr>
</table>

In this example, the header cell "Name" spans two rows.

Merging Columns with colspan

The colspan attribute is used to merge cells horizontally, creating a single cell that occupies the space of multiple columns.

How it Works:

  • You add the colspan attribute to the <td> or <th> tag of the first cell you want to merge.
  • The value of colspan specifies the number of columns that the cell should span.

Example:

<table border="1">
  <tr>
    <th colspan="2">Personal Information</th>
     <th>City</th>
  </tr>
  <tr>
    <td>John Doe</td>
    <td>25</td>
      <td>New York</td>
  </tr>
    <tr>
       <td>Jane Smith</td>
        <td>30</td>
      <td>London</td>
    </tr>
</table>

Here, the header cell "Personal Information" spans two columns.

Key Takeaways:

  • Use rowspan to merge cells vertically (across rows).
  • Use colspan to merge cells horizontally (across columns).
  • The number associated with rowspan or colspan dictates the number of rows or columns, respectively, the cell will span.

By using these attributes, you can create complex and visually appealing HTML tables, especially when needing to combine multiple data categories into a single visual unit.

Related Articles