March 17, 2012

Three table side by side overflow of div container?

Question by StevenChow

I’ve got a problem with my page’s layout.
I want to create 3 table and set them side by side, so I set float attribute of them is “left”, but the height of div container only fix with the 3rd table, two first table is overflow of the div. Please help me to fix it.
Here is my page

<body>

<div id="main">

    <table id="tbSA" class="tb">
        <tr><td>Code</td></tr>
        <tr><td>Code</td></tr>
        <tr><td>Code</td></tr>
        <tr><td>Code</td></tr>
        <tr><td>Code</td></tr>
    </table>

    <table id="tbShops" class="tb">
        <tr><td>Code</td></tr>
        <tr><td>Code</td></tr>
        <tr><td>Code</td></tr>
        <tr><td>Code</td></tr>
    </table>

    <table>
        <tr><td>Code</td></tr>
        <tr><td>Code</td></tr>
        <tr><td>Code</td></tr>
    </table>

</div>
</body>​

and here is style

body {
    background-color: #5c87b2;
}
#main {
    margin: 10px 10px 15px 10px;
    background-color: #fff;
}

table, td {
  border: solid 1px #e8eef4;
}

.tb {
    float:left;
    margin-right:10px;
}​

Answer by Starx

This sort problem is because your first two table are floated. but the last one is not so the div will correctly resize to it to wrap the third table.

But it order to make the div wrap around the floated table too. You have to clear the floats.

There are many ways to solve this:

  1. The safest way is to use, a clearing div just before closing the parent div [Demo]

    <div style="clear:both"></div>
    
  2. Old popular way is to give overflow:hidden which will force the div to wrap around all the elements. This is what other answers are focused out [Demo]

  3. The third way is to use a .clearfix class and is the most popular way nowadays. [Demo]

    .clearfix:after {
        content: ".";
        display: block;
        clear: both;
        visibility: hidden;
        line-height: 0;
        height: 0;
    }
    
    html[xmlns] .clearfix {
        display: block;
    }
    
    * html .clearfix {
        height: 1%;
    }
    

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!