Yarin
Yarin

Reputation: 183999

Expanding a parent div horizontally to fit its floated children

I have a parent div with a variable number of equally sized child divs floated left. I want the parent div to expand to the width of the children no matter what, even if it means overflowing its own container.

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

Example (The stretchable div would wind up being 180px wide):

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;
}

Upvotes: 6

Views: 14329

Answers (3)

Sotiris
Sotiris

Reputation: 40096

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

So a possible css for what you need is this:

#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/

Upvotes: 1

user641656
user641656

Reputation:

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

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

Upvotes: 3

Loktar
Loktar

Reputation: 35319

In this example the stretchable-div element will bust out of 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>

Upvotes: 6

Related Questions