HTML Nested Table
Rumman Ansari
Software Engineer
2023-03-27
6631
Share
☰ Table of Contents
As with many other HTML elements, it is possible to nest tables. That is, part or all of the contents of one cell of an outer table may be another entire table.
However, you need to exercise caution when nesting tables. Even if your HTML is absolutely correct, some people still may not see what you intended. Some browsers may not support nested tables at all, and those that do may not support more than one level of nesting (in other words, a table inside of a table may work, but not a table inside of a table inside of a table).
The good news is that nesting tables are usually unnecessary. You can often re-think the table layout in a way that uses a single, slightly more complex table, and cells joined by COLSPAN and ROWSPAN, to achieve the desired result.
For example, examine the following table layout:
Live Preview
*** View in Full Srreen
One way to conceptualize this layout is as a set of three nested 2 x 2 tables. The outermost table consists of the
cells numbered 1, 2, and 3, plus another cell in the lower right quadrant that is further
subdivided. The next table consists of the cells numbered 6, 9, and 10, plus another cell
in the upper left quadrant that is again further subdivided. This final, innermost, table consists of the cells numbered 4, 5, 7, and 8. Thus it is as if the
following three 2 x 2 tables were nested inside each other (the word "next" in the HTML below is replaced by the code for
the entire next table):
Step 1:
Live Preview
Step 2:
Live Preview
Step 3:
Live Preview
The complete resulting HTML code for this way of looking at this layout is:
Live Preview
In this view, the cell numbered 2 occupies the same position as three horizontally-adjacent cells would in a full 4 x 4 table,
so it uses COLSPAN=3. Likewise, the cell numbered 3 occupies the same position as three vertically-adjacent cells would in the
full table, so it uses ROWSPAN=3. The cells numbered 6 and 9 also represent combined cells (two cells each),
so they use ROWSPAN=2 and COLSPAN=2, respectively. The HTML code for this way of looking at this layout is:
Live Preview
This is shorter, simpler, and much easier to maintain. In addition, it avoids table nesting altogether. Notice that the cell order
differs between the two versions, for browsers which do not support tables at all: the nested version presents cells as
1 2 3 4 5 7 8 6 9 10 (cell 6 is out of sequence), whereas the other version presents them in the order they
were numbered for this example. Which ordering is correct, of course, depends on your point-of-view (the numbers are arbitrary).
Live Preview
Final Result
Live Preview
Another Example
|
Morning |
Afternoon |
Saturday |
Cycling |
Fishing |
Sunday |
Rowing |
Group 1 |
Group 2 |
Water ski-ing |
Wake boarding |
|