Search code examples
htmlcssalignment

Two DIVs next to each other without width parameter ( width: auto; )


I am trying to figure out, how to place two divs next to each other without specifying the width. It is not as easy as it seems:

the HTML:

    <div id="container">
     <div id="column1">Fixed Width</div>
     <div id="column2">Auto Width</div>
    </div>

the CSS:

    #container {
     float:left;
     width:200px;
    }
    #column1 {
     float:left;
     width:24px;
     background:gray;
    }
    #column2 {
     float:left;
     width:auto;
     background:blue;
    }

*the #container has 200px fixed width (could be XX%). #column1 has a fixed width of 24px, #column2 has the width set to auto.

This will work just fine and column2 will be next to column1, until the contents of column2 will reach the limit of 200-24 where, instead of a line break inside the div, column2 will jump below column1.

What I am trying to achieve (bulletproof) that column2 stays next to column1, inside container, no matter how big the content of column2 gets. Height is auto and does not matter.

(I am trying to create a message box, similar to Facebook, thumbnail on the left side, text next to it with unlimited height. I don't want the text from column2 to jump below or wrap around column1). May be very easy, could not figure it out. As always, any help would be highly appreciated! :)


Solution

  • If you remove float property from #column2 and set display: table; you will get desired effect.

    HTML

      <div id="container">
         <div id="column1">Fix</div>
         <div id="column2">Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum </div>
      </div>
    

    CSS

        #container {
         float:left;
         width:200px;
        }
        #column1 {
         float:left;
         width:24px;
         background:gray;
        }
        #column2 {
         background:blue;
        display: table;
        }
    

    DEMO

    Try to remove or add more "Lorem Ipsum" text.