Expanding the parent div horizontally to accommodate its floating children

I have a parent div with a variable number of child divs with the same size placed on the left. I want the parent div to expand to the width of the children, no matter what, even if it means overflowing its container.

Is there a way to do this naturally with HTML / CSS?

Example (a stretch div will have a width of 180 pixels):

HTML:

<div id="stretchable-div"> <div class="child"></div> <div class="child"></div> <div class="child"></div> ... </div 

CSS

 .child { width: 60px; height: 60px; float:left; } 
+6
html css layout
source share
3 answers

In this example, the stretchable-div element will exit its parent and stretch to its children.

Live demo

CSS

 #parent{ width:200px; height:180px; background:red; } #stretchable-div{ background:blue; position: absolute; } .child { width: 60px; height: 60px; float:left; } 

Markup

 <div id="parent">Im a parent <div id="stretchable-div"> <div class="child">a</div> <div class="child">b</div> <div class="child">c</div> <div class="child">c</div> <div class="child">c</div> <div class="child">c</div> <div class="child">c</div> </div> </div> 
+5
source share

Like the @Pizzicato example, but using overflow:hidden to clear the parent div : http://jsfiddle.net/dSjv4/ .

Here's a great article on posting and clearing a div on A List Apart here (near the end of the article).

+3
source share

you can add display: inline-block; for the parent element. To work in ie7 you also need to use display:inline;zoom:100%; .

So, a possible css for you is needed:

 #stretchable-div { background: none repeat scroll 0 0 red; display: inline-block; overflow: auto; /* clear the floats */ *display:inline; /* ie7 hack even better use conditional comment */ zoom:100%; } 

example: http://jsfiddle.net/8JJSf/

+1
source share

All Articles