Search code examples
jqueryhtmlcssnested-table

Align Nested Table Headers Using jQuery


I have a standard html table and inside its rows there are nested tables. These nested tables are generated by a plugin and I have no choice but to use this layout.

The problem I am facing is that the nested tables fit inside the second column of the parent table. And I need to put headers above the nested table columns and vertically align them with the header for the first column of parent table.

I would like to achieve this using jQuery. I have made an example of how my current layout looks like, the column headers that I wish to align have been given a background color of red. Here is the example: http://jsfiddle.net/Qh66H/

<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">        </script>
</head>
<body>
<table class="outer-table">
<thead>
    <th>Heading 1</th>
</thead>
<tbody>
    <tr>
        <td>
            Content 1
        </td>
        <td>
            <table>
                <thead>
                    <th>Heading 1.1</th>
                    <th>Heading 1.2</th>
                </thead>
                <tbody>
                    <tr>
                        <td>
                            Content 1.1
                        </td>
                        <td>
                            Content 1.2
                        </td>
                    </tr>
                </tbody>
            </table>
        </td>
    </tr>
    <tr>
        <td>
            Content 2
        </td>
        <td>
            <table>
                <thead>
                    <th>Heading 2.1</th>
                    <th>Heading 2.2</th>
                </thead>
                <tbody>
                    <tr>
                        <td>
                            Content 2.1
                        </td>
                        <td>
                            Content 2.2
                        </td>
                    </tr>
                </tbody>
            </table>
        </td>
    </tr>
</tbody>
</table>
</body>

<script>
    function styleHeaders(){
    //Hide all except the first nested headers.
    $(".outer-table table").find("thead").not(":eq(0)").css('display', 'none');

    //Move first nested table header up.
    $(".outer-table table").find("thead:eq(0)").css('background-color', 'red');
}

styleHeaders();
</script>

</html>

I hope someone can help, thank you.


Solution

  • Would a negative margin be a good enough work around ? DEMO

    table tr:first-of-type table {
        margin:-1.6em 0 0;/* needs to be tuned to numbers of lines + border-spacing */
    }
    

    <edit> okay, just seeing answers already given via class + j query </edit>