How to merge cells in an HTML Table

Hello everyone! In this tutorial, we will learn how to merge cells in an HTML table.

Before we go forward, let’s define our HTML table first:

<table border="2">
  <tr>
    <th>Student</th>
    <th>Roll No</th>
    <th>Department</th>
  </tr>
  <tr>
    <td>Amit</td>
    <td>53</td>
    <td>IT</td>
  </tr>
  <tr>
    <td>Jeet</td>
    <td>89</td>
    <td>COMP</td>
  </tr>
</table>

<table> tag is been used in HTML to define tables. For table header <th> tag is been used which is by default bold and centered and for each table row in a table <tr> tag is been used and to define a Table data <td> tag is been used.

Now let’s learn how to do our task…

Merging of cells in an HTML Table

<table border="2">
  <tr>
    <th rowspan="2">Student</th>
    <th colspan="3">Subject</th>
  </tr>
  <th>Java</th>
  <th>Java Script</th>
  <th>Python</th>
  <tr>
    <td>Amit</td>
    <td>53</td>
    <td>89</td>
    <td>78</td>
  </tr>
  <tr>
    <td>Jeet</td>
    <td>89</td>
    <td>88</td>
    <td>78</td>
  </tr>
</table>

Now consider this table where Student is a span of more than 2 rows and the cell containing Subject is been merged with Java, JavaScript, Python to form a single cell.

Now how can we define such tables? We can define such tables by using rowspan and colspan attributes in <th> tag of the table!

The rowspan attribute in our <th> tag is able to merge two or more rows. On the other hand, the colspan attribute is been used to merge two or more columns.

Also, read:

We have to inputs that are rowspan and colspan attribute with the <th> tag like <th rowspan=”2″> or <th colspan=”3″> where 2 and 3 are the numbers to merge the cells in a row and column then we have to give the heading to the merge cells with the <th> tag just like I have given in the code like <th>Java</th> this will merge with <th colspan=”3″>Subject</th>.

If any queries related to the topic, let me know in the comment section and I will be happy to help you out!

Leave a Reply

Your email address will not be published. Required fields are marked *