Search code examples
htmlcsshtml-tablecenter

CSS/HTML display tables inline until they exceed parent div's width?


How do I display two tables right next to each other until one of them grows too large in width?

If this happens I want the right hand-side table to show up below the first (left hand-side) table and both tables being centered within their parent <div>.

This is what I got so far:

<!-- center div in the middle of the page -->
<div style="width: 80%; margin-left: auto; margin-right: auto">
    <table style="float: left; min-width: 50%">
        <tr><th>Header table 1</th></tr>
        <tr><td>Row1</td></tr>
    </table>
    <table style="float: left; min-width: 50%">
        <tr><th>Header table 2</th></tr>
        <tr><td>Row1</td></tr>
    </table>
    <div style="clear: both"></div>
</div>

I put some long text string into table1's Row1-cell to make it exceed its min-width and the result was that table2 dropped below table1, but the float:left kept both tables glued to the left side of their parent <div>:

+-------------------------+
|+-----+                  |
|| t1  |                  |
|+-----+                  |
|+-----+                  |
|| t2  |                  |
|+-----+                  |
|                         |
|          div            |
+-------------------------+

What I want it to look like if one of the tables grows too large in width to display them in a row:

+-------------------------+
|         +-----+         |
|         | t1  |         |
|         +-----+         |
|         +-----+         |
|         | t2  |         |
|         +-----+         |
|                         |
|          div            |
+-------------------------+

How do I achieve that?


Solution

  • See if this will work for you: jsFiddle

    HTML:

    <div>
        <table>
            <tr><th>Header table 1</th></tr>
            <tr><td>Row1</td></tr>
        </table>
        <table>
            <tr><th>Header table 2</th></tr>
            <tr><td>Row1</td></tr>
        </table>
    </div>
    

    CSS:

    * {margin:0; padding:0; outline:none;} div {width:80%; margin:0 auto; text-align:center; overflow:hidden; background:#ddd;} table {display:inline-block; min-width:49%; background:#ccc;}