Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expanding a parent div horizontally to fit its floated children

Tags:

html

css

layout

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;
}
like image 707
Yarin Avatar asked Mar 14 '11 18:03

Yarin


1 Answers

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>
like image 85
Loktar Avatar answered Sep 30 '22 11:09

Loktar