26

I want to place two DIV tags side by side without using fixed width. The first div expands to its content and the second div should fill the remaining space. Also the div must NOT sit on top of the other div, because they have a transparent background image so if they intersect it's noticeable. I tried all possibilities that i could think off but couldn't find a solution using DIV tags.

I can do this using a TABLE, but is it possible to do it using DIV's? Or is this one more thing DIV's can't do?

Here's the code:

            #right{
              background: green;     
              width: 100%;
            }
            #left {
              margin-top: 5px; /* to test if they intersect*/
              background: red;
            }  
            #container {
               width: 800px;
            }
            <div id="container">
               <div id="left"> This div is as big as it's content</div>
               <div id="right"> rest of space</div>
            </div> 

Thanks for the replies!

blejzz
  • 3,349
  • 4
  • 39
  • 60

1 Answers1

68

See: http://jsfiddle.net/kGpdM/

#left {
    background: #aaa;
    float: left
}
#right {
    background: cyan;
    overflow: hidden
}

This works in all modern browsers and IE7+.

The left column will be exactly as wide as the content inside it. The right column will take the remaining space.

The overflow: hidden "trick" behind this answer is explained here.

thirtydot
  • 224,678
  • 48
  • 389
  • 349
  • I still don't understand why this works, but it works. But can we reliably trust that this will continue to work into the future? – Vincent Feb 26 '16 at 23:34
  • @Vincent: Yes, it's guaranteed to work in the future, the behaviour is well defined somewhere in the CSS spec. Another way to do this is with `display: table-cell`, [here's an example](http://stackoverflow.com/questions/6938900/how-can-i-put-an-input-element-on-the-same-line-as-its-label/6938990#6938990). – thirtydot Feb 26 '16 at 23:42
  • The downside of this is that you have something in the overflow hidden area that dynamically need to pass through (like dropdown menu), it will be cut off. – NenadP Mar 08 '16 at 10:57
  • @NenadP: That's true, in that case you have to use a different approach such the `display: table-cell` approach I linked to in my previous comment. – thirtydot Mar 08 '16 at 11:42