Search code examples
htmlalignmentwidthcss-tables

Two tables above each other where the visual width for both is the larger of the two


I have two tables that I'd like to stack one on top of the other so that visually they appear to be one entity - the width of both should be equal.

For arguments sake, lets say the top table has 8 columns and the bottom will have 3 columns. How do I get it so that the bottom table occupies the same visual width as the top table?

The reason I want this is because the top table is loaded with radio buttons and checkbox items, and the lower table will always have only one row consisting of a cancel button, a quantity field and an OK button. I have dozens of different top tables of various widths but I want to code only one of the bottom table and with Javascript haul in one of the top tables and put the lower table below it so it occupies the same width as that top table.

I'm stuck on the html and / or CSS to get the widths the same. I'm not adamant about the lower thing being a table. If there's a solution that will give me those 3 fields nicely centered within the width of the top table, that's great.


Solution

  • I think you're looking for something like this:

    Working Example

    CSS

    table {
        border:1px solid blue;
    }
    .table1 td {
        border:1px solid red;
        height:50px;
        width:50px;
    }
    .table2 td {
        height:50px;
        border: 1px solid green;
    }
    

    HTML

    <table class="table1">
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
    </table>
    <table class="table2">
        <td></td>
        <td></td>
        <td></td>
    </table>
    

    jQuery

    var width = function () {
        $('.table2').width($('.table1').width());
    };
    
    $(document).ready(width);
    $(window).resize(width);
    

    If you prefer pure JavaScript:

    Working Example2

    function tablewidth() {
        var table1 = document.getElementById('table1'),
            style = window.getComputedStyle(table1),
            width = style.getPropertyValue('width'),
            border = style.getPropertyValue('border-left-width'),
            w = parseInt(width, 10) + parseInt(border, 10) * 2 + 'px';
    
        document.getElementById('table2').style.width = w;
    }
    window.onresize = tablewidth;
    window.onload = tablewidth;