我们从哪里开始
这是一些样板HTML和CSS。在我们的示例中,我们有一个带有两个浮动子元素的父元素。
/* The CSS you're starting with may look similar to this.
* This doesn't solve our problem yet, but we'll get there shortly.
*/
.containing-div {
background-color: #d2b48c;
display: block;
height: auto;
}
.floating-div {
float: left;
width: 50%;
}
.floating-div ul {
display: inline-block;
height: auto;
}
<!-- The HTML you're starting with might look similar to this -->
<div class="containing-div">
<div class="floating-div">
<ul>
<li>List Item One</li>
<li>List Item Two</li>
<li>List Item Three</li>
<li>List Item Four</li>
</ul>
</div>
<div class="floating-div">
<ul>
<li>List Item Five</li>
<li>List Item Six</li>
<li>List Item Seven</li>
<li>List Item Eight</li>
</ul>
</div>
</div>
解决方案#1:溢出:自动
在所有现代浏览器中以及在IE8和IE8中均可使用的解决方案是将其添加overflow: auto
到父元素。在IE7中,添加滚动条也可以使用。
/* Our Modified CSS.
* This is one way we can solve our problem.
*/
.containing-div {
background-color: #d2b48c;
display: block;
height: auto;
overflow: auto;
/*This is what we added!*/
}
.floating-div {
float: left;
width: 50%;
}
.floating-div ul {
display: inline-block;
height: auto;
}
解决方案2:浮动父容器
适用于所有现代浏览器并返回IE7的另一种解决方案是浮动父容器。
这可能并不总是可行的,因为浮动父div可能会影响页面布局的其他部分。
/* Modified CSS #2.
* Floating parent div.
*/
.containing-div {
background-color: #d2b48c;
display: block;
float: left;
/*Added*/
height: auto;
width: 100%;
/*Added*/
}
.floating-div {
float: left;
width: 50%;
}
.floating-div ul {
display: inline-block;
height: auto;
}
方法3:在浮动元素下添加Clearing Div
/*
* CSS to Solution #3.
*/
.containing-div {
background-color: #d2b48c;
display: block;
height: auto;
}
.floating-div {
float: left;
width: 50%;
}
.floating-div ul {
display: inline-block;
height: auto;
}
/*Added*/
.clear {
clear: both;
}
<!-- Solution 3, Add a clearing div to bottom of parent element -->
<div class="containing-div">
<div class="floating-div">
<ul>
<li>List Item One</li>
<li>List Item Two</li>
<li>List Item Three</li>
<li>List Item Four</li>
</ul>
</div>
<div class="floating-div">
<ul>
<li>List Item Five</li>
<li>List Item Six</li>
<li>List Item Seven</li>
<li>List Item Eight</li>
</ul>
</div>
<div class="clear"></div>
</div>
方法4:向父元素添加Clearing Div
此解决方案对于较旧的浏览器和较新的浏览器都非常安全。
/*
* CSS to Solution #4.
*/
.containing-div {
background-color: #d2b48c;
display: block;
height: auto;
}
.floating-div {
float: left;
width: 50%;
}
.floating-div ul {
display: inline-block;
height: auto;
}
/*Added*/
.clearfix {
clear: both;
}
.clearfix:after {
clear: both;
content: "";
display: table;
}
<!-- Solution 4, make parent element self-clearing -->
<div class="containing-div clearfix">
<div class="floating-div">
<ul>
<li>List Item One</li>
<li>List Item Two</li>
<li>List Item Three</li>
<li>List Item Four</li>
</ul>
</div>
<div class="floating-div">
<ul>
<li>List Item Five</li>
<li>List Item Six</li>
<li>List Item Seven</li>
<li>List Item Eight</li>
</ul>
</div>
</div>
来自https://www.lockedownseo.com/parent-div-100-height-child-floated-elements/