Search code examples
htmldynamichtml-tableheadermulti-level

Construct a HTML table with irregular Multilavel Header


I would like to construct a table as follows:

|   Major Heading 1   |   Major Heading 2   |   Major Heading 3   |  Major Heading 4 |
|                     |  Minor1  |  Minor2  |  Minor1  |  Minor2  |                  |  more similar headers ...
--------------------------------------------------------------------------------------
|   col1   |   col2   |   col3   |   col4   |   col1   |   col2   |   col3  |  col4  |
rest of table ...

There are two types of header, one with sub-header and one only single. I have tried, single header with rowspan and colspan is 2. For the multilevel, main header will have rowspan 1 and colspan 2 and for sub-header it will colspan 1 and rowspan 1.

I have also tried with adding nester after multilevel header . But it's breaking the table. Can anyone give me some idea to to construct the table using html only without any css?


Solution

  • Solution I figured out for this requirement is to maintain two row <tr> for Header and Subheader. And,

    • All Headers should have equal colspan="2" (double of Subheader colspan),
    • Headers without Subheader will have rowspan="2" (double of Header with Subheader and it's rowspan)
    • Headers with Subheader will have rowspan="1" (equal of Subheader rowspan)
    • Subheaders have to follow the order of respective Headers

    Working example,

    <!DOCTYPE html>
    <html>
        <head>
            <style>
                table {
                    border-collapse: collapse;
                    width: 100%;
                }
                td,
                th {
                    border: 1px solid #dddddd;
                    text-align: center;
                    padding: 8px;
                }
            </style>
        </head>
        <body>
            <table>
                <tr>
                    <th colspan="2" rowspan="2">Head 1</th>
                    <th colspan="2" rowspan="1">Head 2</th>
                    <th colspan="2" rowspan="2">Head 3</th>
                </tr>
                <tr>
                    <th rowspan="1">Subhead 2.1</th>
                    <th rowspan="1">Subhead 2.2</th>
                </tr>
                <tr>
                    <td>Col 1</td>
                    <td>Col 2</td>
                    <td>Col 3</td>
                    <td>Col 4</td>
                    <td>Col 5</td>
                    <td>Col 5</td>
                </tr>
            </table>
        </body>
    </html>