There are instances where you would be asked to define headers in multiple rows.
So, in the above table there are two header rows. The first row represents the details of Students of class 5 and Students of class 7.
And the second row has the Name and Roll as header.
The above table can be defined in HTML using the colspan attribute with the TH element.
<html> <body> <table border = "1"> <tr> <th colspan="2">Students of class 5</th> <th colspan="2">Students of class 7</th> </tr> <tr> <th>Name</th> <th>Roll</th> <th>Name</th> <th>Roll</th> </tr> <tr> <td>John</td> <td>2</td> <td>Salim</td> <td>12</td> </tr> <tr> <td>Paul</td> <td>3</td> <td>Kriti</td> <td>13</td> </tr> <tr> <td>Mohan</td> <td>4</td> <td>Tom</td> <td>14</td> </tr> </table> </body> </html>
So to define the header in the second row,
We have used the th tags(As we have seen in earlier tutorials).
Now, to define the header in the first row,
We need to merge two columns. And colspan is used to merge two columns.
So, if you look at the value of colspan, it is 2.
<th colspan="2">Students of class 5</th> <th colspan="2">Students of class 7</th>
It says, merge two columns for the headers Students of class 5 and Students of class 5.
Similarly, if we want to define the below table,
We would have to use the value of colspan as 4 for the first row(i.e. For the header Student). As rest of the code would just be the same.
<html> <body> <table border = "1"> <tr> <th colspan="4">Student</th> </tr> <tr> <th colspan="2">Students of class 5</th> <th colspan="2">Students of class 7</th> </tr> <tr> <th>Name</th> <th>Roll</th> <th>Name</th> <th>Roll</th> </tr> <tr> <td>John</td> <td>2</td> <td>Salim</td> <td>12</td> </tr> <tr> <td>Paul</td> <td>3</td> <td>Kriti</td> <td>13</td> </tr> <tr> <td>Mohan</td> <td>4</td> <td>Tom</td> <td>14</td> </tr> </table> </body> </html>
In the above code we have merged four columns for the first row. And have used the value of colspan as 4.
<th colspan="4">Student</th>