我们可以看到这样一个布局:
<style>
.left{
width: 200px;
height: 200px;
background-color: #00ee00;
float: left;
}
.right{
width: 100px;
height: 200px;
background-color: #0000FF;
float: left;
}
.footer{
width: 300px;
height: 50px;
background-color: #0f0f0f;
}
</style>
<div class="content">
<div class="left"></div>
<div class="right"></div>
</div>
<div class="footer"></div>
我们预期效果: 结果:
原因:因为父盒子没有给高,然后content内的子元素又是左浮动,脱离标准流,然后下面的footer就会跑上去,这是因为浮动问题产生的,如何解决:
方法1:使用clear:both
<style>
.left{
width: 200px;
height: 200px;
background-color: #00ee00;
float: left;
}
.right{
width: 100px;
height: 200px;
background-color: #0000FF;
float: left;
}
.footer{
width: 300px;
height: 50px;
background-color: #0f0f0f;
}
.clearfix{
clear: both;
}
</style>
<div class="content">
<div class="left"></div>
<div class="right"></div>
<div class="clearfix"></div>
</div>
<div class="footer"></div>
方法二:使用overflow:hidden;
<style>
.content{
overflow: hidden;
}
.left{
width: 200px;
height: 200px;
background-color: #00ee00;
float: left;
}
.right{
width: 100px;
height: 200px;
background-color: #0000FF;
float: left;
}
.footer{
width: 300px;
height: 50px;
background-color: #0f0f0f;
}
</style>
<div class="content">
<div class="left"></div>
<div class="right"></div>
</div>
<div class="footer"></div>
第三种(推荐):clearfix伪类
<style>
.left{
width: 200px;
height: 200px;
background-color: #00ee00;
float: left;
}
.right{
width: 100px;
height: 200px;
background-color: #0000FF;
float: left;
}
.footer{
width: 300px;
height: 50px;
background-color: #0f0f0f;
}
.clearfix:after{
content: "";
display: block;
clear: both;
height: 0;
line-height: 0;
visibility: hidden;
}
.clearfix{
zoom: 1;//兼容ie浏览器
}
</style>
<div class="content clearfix">
<div class="left"></div>
<div class="right"></div>
</div>
<div class="footer"></div>