Left align two tables while keeping the first (with fluid width) centered

advertisements

The page consists of two tables (golf scores). The first, which is always wider than the second, includes two columns of names and therefore its total width will vary from league to league. The second table only contains numbers and its width will be constant.

I want to align the left edge of the two tables while keeping the first table centered.

If I knew the width of the first table then the issue would be simple, use css to set the html width to that of the table and set the two table left margins to 0. But with the width being fluid the tables move with different content. How do I solve this dilemma?


Here is a fairly easy and robust way of solving this problem.

First, create a wrapper elements to contain the two tables, .wrap in my example.

On .wrap, set display: table and margin: 0 auto. This will force .wrap to take a shrink-to-fit width, and then the margin trick will center the block.

Your two child tables will then be aligned to the left by default.

.wrap {
    display: table;
    border: 1px dashed blue;
    margin: 0 auto;
}
table {
    border: 1px dotted blue;
    margin: 20px;
}
table td {
    border: 1px solid gray;
}
<div class="wrap">
    <table>
        <tr>
            <td>First Wide Column With Long Names</td>
            <td>Second Wide Column with Very Long Names</td>
        </tr>
    </table>
    <table>
        <tr>
            <td>First Short Column</td>
            <td>Second Short Column</td>
        </tr>
    </table>
</div>

You can also see jsfiddle at: http://jsfiddle.net/audetwebdesign/qt5ffzuo/