Expand container div with content width

Andre picture Andre · May 24, 2011 · Viewed 87k times · Source

I have the following structure in my application:

<div id="container">
  <div id="child_container">
    <div class="child"></div>
    <div class="child"></div>
    ...
    <div class="child"></div>
  </div>
</div>

Each child div has a known fixed width, but the application allows more of them to be inserted in the child_container div.

What I'm trying to do is to have the container div expand horizontally when needed, given the total width of the child container.

This is what happens currently:

+------ container -------+
+--- child_container ----+
| child1 child2 child3   |
| child4                 |
+------------------------+

If I set the child_container div width to a fixed value, I can get it to expand horizontally past the container div, which works despite being a bit ugly:

+------ container -------+
+------ child_container -+----+
| child1 child2 child3 child4 |
+------------------------+----+

However, that requires recalculating it whenever a new child is added.

Is there a way to do this without using fixed widths for child container, in a way such that the end result is

+--------- container ---------+
+------ child_container ------+
| child1 child2 child3 child4 |
+-----------------------------+

Thanks.

Answer

wajiw picture wajiw · May 24, 2011

Something like this should work:

#container, #child_container, .child { 
    position: relative; 
    float: left;
}