简体   繁体   English

如何使浮动div容器适合div高度?

[英]How to make floated div container fit to the div height?

I have a div container #parent and a div child #child who's child of the parent div . 我有一个div容器#parent和一个div子#child是父div的孩子。

The #child div contain text and he is floated left, the problem is that I want the #parent div to fit the height of the #child` div what ever the height is with keeping the float property also . #child div包含文本并且他向左浮动,问题是我希望#parent div适合#child` div的高度,保持float属性的高度也是如此。

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

Here is a Jsfiddle 这是一个Jsfiddle

Add overflow:auto to the parent: 添加overflow:auto到父级:

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

jsFiddle example jsFiddle例子

When you float the child, the parent collapses because it's acting as if the child occupies no space. 当您浮动孩子时,父母会崩溃,因为它的行为就好像孩子不占空间一样。 Adding the overflow rule restores the behavior that you're after. 添加溢出规则可恢复您所追求的行为。

Check out the Demo 看看演示

One way to do it is with ":after" selector. 一种方法是使用“:after”选择器。

HTML HTML

<div id='parent'>

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

</div>

CSS CSS

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

Use clearfix. 使用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/ http://jsfiddle.net/XgErJ/463/

Method :1 方法:1

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

    #child{
       float:left;
      }

http://jsbin.com/yufezamofo/3/ http://jsbin.com/yufezamofo/3/

Method:2 方法:2

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

    #child{
       float:left;
      display:table-cell;
      }

http://jsbin.com/yufezamofo/2/ http://jsbin.com/yufezamofo/2/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM