How to create custom tables in HTML?

Programming | 14 May 2019

I always wondered is there a way to create tables like the one shown below without using nested tables (i.e., table inside a table by hacking border property in CSS).

Gender Average Red Eyes
Height Weight
Males 165 65 30%
Females 150 50 45%

If you want to create the above table using nested tables concept, you would give up on the width of your table’s td elements. Based on your td content, the width property will vary, and eventually you mess up with the borders and finally, you have a messy table with misaligned borders!

One hack is to use a fixed width for your td elements and fill up the content based on that with overflow: auto enabled in CSS. But, that’s not the best solution to this problem.


To solve this problem, we need to preserve the width of the td elements somehow. And the best solution is to take a pen and paper!

  1. Draw the table that you expect using a pen and paper to clearly understand the layout that you’re going to code.

  2. After figuring out the layout, use rowspan and colspan attributes for your td elements to bring that customized table (without any nested tables concept). It’s that simple 😊

You can look at the below code and output to understand rowspan and colspan better.

index.htmlcode
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
<table>
  <tr>
    <td rowspan="3">Country</td>
  </tr>
  <tr>
    <td rowspan="2">Region</td>
  </tr>
  <tr>
    <td>Product</td>
    <td>Profit</td>
  </tr>
  <tr>
    <td rowspan="6">India</td>
    <td rowspan="2">Western</td>
    <td>Monitor</td>
    <td>10</td>
  </tr>
  <tr>
    <td>Desk Lamp</td>
    <td>20</td>
  </tr>
  <tr>
    <td rowspan="2">Central</td>
    <td>Monitor</td>
    <td>30</td>
  </tr>
  <tr>
    <td>Desk Lamp</td>
    <td>25</td>
  </tr>
  <tr>
    <td rowspan="2">Eastern</td>
    <td>Monitor</td>
    <td>31</td>
  </tr>
  <tr>
    <td>Desk Lamp</td>
    <td>17</td>
  </tr>
</table>
Country
Region
Product Profit
India Western Monitor 10
Desk Lamp 20
Central Monitor 30
Desk Lamp 25
Eastern Monitor 31
Desk Lamp 17

In case if you found something useful to add to this article or you found a bug in the code or would like to improve some points mentioned, feel free to write it down in the comments. Hope you found something useful here.