簡體   English   中英

如何使浮動div容器適合div高度?

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

我有一個div容器#parent和一個div子#child是父div的孩子。

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

這是一個Jsfiddle

添加overflow:auto到父級:

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

jsFiddle例子

當您浮動孩子時,父母會崩潰,因為它的行為就好像孩子不占空間一樣。 添加溢出規則可恢復您所追求的行為。

看看演示

一種方法是使用“: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;
}

使用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/

方法:1

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

    #child{
       float:left;
      }

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

方法:2

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

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM