How to make a div grow in height while having floats inside

混江龙づ霸主 提交于 2019-11-28 13:40:48

问题


How can I make a div grow its height when it has floats inside of it? I know that defining a value for the width and setting overflow to hidden works. The problem is that I need a div with the overflow visible. Any ideas?


回答1:


overflow:auto; on the containing div makes everything inside of it (even floated items) visible and the outer div fully wraps around them. See this example:

.wrap {
  padding: 1em;
  overflow: auto;
  background: silver;
 }
 
.float {
  float: left;
  width: 40%;
  background: white;
  margin: 0 1%;
}
<div class="wrap">
  <div class="float">Cras mattis iudicium purus sit amet fermentum. At nos hinc posthac, sitientis piros Afros. Qui ipsorum lingua Celtae, nostra Galli appellantur. Petierunt uti sibi concilium totius Galliae in diem certam indicere. Ambitioni dedisse scripsisse iudicaretur.</div>
  <div class="float">Mercedem aut nummos unde unde extricat, amaras. A communi observantia non est recedendum. Quisque ut dolor gravida, placerat libero vel, euismod. Paullum deliquit, ponderibus modulisque suis ratio utitur.</div>
  </div>



回答2:


There's more than one way to clear floats. You can check some here:
http://work.arounds.org/issue/3/clearing-floats/

E.g., clear:both might work for you

#element:after {
    content:"";
    clear:both;
    display:block;
}

#element { zoom:1; }



回答3:


In many cases, overflow: auto; will be enough, but for the sake of completion and cross browser support, have a look at Clearfix which will do the job for all browsers.

Lets consider the following markup..

<div class="clearfix">
   <div class="content">Content 1</div>
   <div class="content">Content 2</div>
</div>

Along with the following styles..

.content { float:left; }

.clearfix { ..from link.. }

Without the clearfix, the parent div wouldn't have a height due to it's floating children. The clearfix will make the parent consider the floating children.




回答4:


I figured that a great way to do it is setting display: table on the div.



来源:https://stackoverflow.com/questions/4604005/how-to-make-a-div-grow-in-height-while-having-floats-inside

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!