Introduction
HTML tables are a fundamental part of web development. They allow you to organize & display data in a structured way on your web pages. Two important attributes that enhance the functionality of HTML tables are "colspan" & "rowspan". These attributes help you to merge cells horizontally or vertically, creating more complex table layouts.
In this article, we will learn how to use colspan & rowspan in HTML tables, along with examples to understand their use.
HTML Table with Colspan
The "colspan" attribute in HTML tables allows you to merge cells horizontally. When you apply the colspan attribute to a table cell (<td> or <th>), it spans across multiple columns, effectively combining them into a single cell.
To use the colspan attribute, you simply need to add it to the opening tag of the cell & specify the number of columns you want the cell to span. For example, if you want a cell to span across two columns, you would use colspan="2".
For example :
Output
In this example, the second <th> element has a colspan="2" attribute, which means it spans across two columns. The "Contact" header effectively merges the email & phone number columns into a single cell.
When you use colspan, the merged cell takes up the space of the specified number of columns, & the remaining cells in the row adjust accordingly. It's important to ensure that the total number of cells in each row matches the number of columns in the table, taking into account any merged cells.
Example
Now, let's take a look at a more comprehensive example to understand how colspan can be used in real-world situations.
Consider a table that displays a student's report card:
Output
In this example, we have a table with five rows & three columns. The last two rows use the colspan attribute to merge the "Subject" & "Marks" columns.
The fourth row has <td colspan="2">Total Marks</td>, which combines the "Subject" & "Marks" columns into a single cell with the text "Total Marks". The total marks value is then displayed in the third column.
Similarly, the fifth row uses <td colspan="2">Average Grade</td> to merge the "Subject" & "Marks" columns, displaying the text "Average Grade". The average grade value is shown in the third column.