水平扩展父div以适合其浮动的子项

时间:2011-03-14 18:50:23

标签: html css layout

我有一个父div,左边有一个可变数量的大小相同的子div。我希望父div扩展到子节点的宽度,无论如何,即使它意味着溢出它自己的容器。

有没有办法用HTML / CSS自然地做到这一点?

示例(可拉伸的div最终会变宽180px):

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

3 个答案:

答案 0 :(得分:5)

在这个例子中,stretchchable-div元素将从其父元素中消失,并延伸到其子元素。

<强> Live Demo

<强> CSS

#parent{
    width:200px;
    height:180px; 
    background:red;
}

#stretchable-div{
    background:blue;
    position: absolute;
}

.child {
   width: 60px;
   height: 60px;
   float:left;
}

<强>标记

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

答案 1 :(得分:3)

就像@ Pizzicato的例子一样,但使用overflow:hidden清除父divhttp://jsfiddle.net/dSjv4/

有一篇关于在A List Apart here(在文章末尾附近)定位和清除div的文章很棒。

答案 2 :(得分:1)

您可以为父元素添加display: inline-block;。要在ie7中工作,您还需要使用display:inline;zoom:100%;

所以你需要的可能是css:

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

示例: http://jsfiddle.net/8JJSf/

相关问题