如何使浮动的 div 容器与 div 高度相适应?

4
我有一个 div 容器 #parent 和一个 div 子元素 #child,它是父 div 的子元素。

#child div 包含文本并向左浮动,问题是我希望 #parent div 适应 #child` div 的高度,无论高度如何,同时保持浮动属性。

    #parent{
       background: red;
       height: auto;
    }

    #child{
       float:left;
    }
    <div id='parent'>
        <div id='child'>
           <p>Some text Some text Some text</p>
        </div>  
    
    </div>

这里有一个Jsfiddle

4个回答

7

在父元素上添加 overflow:auto

#parent {
    background: red;
    height: auto;
    overflow:auto;
}
#child {
    float:left;
}

当你使用float属性浮动子元素时,父元素会因为表现得好像子元素没有占用空间而发生塌陷。添加overflow属性规则可以恢复你想要的行为。

jsFiddle示例


2

0

请查看演示

一种实现方法是使用“:after”选择器。

HTML

<div id='parent'>

    <div id='child'>
       <p>Some text Some text Some text</p>
    </div>  

</div>

CSS

#parent{
   background: red;
}
#parent:after {
   content:'';
   display:block;
   clear: both;
}
#child{
   float:left;
}

0
使用 clearfix。
.clearfix:after {
             visibility: hidden;
             display: block;
             font-size: 0;
             content: " ";
             clear: both;
             height: 0;
    }
.clearfix { 
   display: inline-block; 
    }
            /* start commented backslash hack \*/
    * html .clearfix { 
     height: 1%; 
    }
    .clearfix { 
    display: block; 
    }
      /* close commented backslash hack */

http://jsfiddle.net/XgErJ/463/


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接