Sunday, December 6, 2015

How to merge cells in HTML Table

In HTML table, merging cells is a very common work to do. The term "merging cells" means  joining  two or more columns / rows.

Ok, let's have an example on this. The Image given below is a schedule table. If you notice closely many cells are merged in this table, some vertically and  some horizontally.

Image 1: A Schedule Table created by excel
This table is created in excel which is very easy to do. But if someone wants to build this same table by using HTML. It is not that hard either. Just need to add an attribute in td tag of the  HTML table. I'll explain it latter, but first check out the HTML code here.  

Image 2: The same Schedule Table Created by HTML
In Image 2 you can see the output. From the mentioned link you can see that in td tag of the table I have used two types of attributes. One is rowspan, another one is colspan. rowspan merges rows that means it will work vertically. On the other hand colspan will work horizontally, meaning it will join columns together. The digit after this attribute states the number of the cells will be merged. So, if we use rowspan="2" that means we are merging 2 rows.

Image 3a: HTML Table td tag
In Image 3a we can see snippet of the HTML code where I have merged 2 rows and 6 columns for placing "Days" and "Time".



The most interesting situation happened when I had to place "Thesis" in the table. If you look carefully in Image 1, for placing "Thesis" I had to merge two rows and two columns at the same time. For doing this we can use rowspan and colspan together in the td.

Image 3b: Merging rows and columns at same time

In Image 3b check the selected line. Here I have used rowspan and colspan together to merge rows and columns at the same time.




This process makes the table look less clumsy and easily understandable. 

2 comments: