六种方法中,推荐使用第三种。
1、父级div定义 height 原理:手动设置父级div的height,解决了父级div无法自动获取高度的问题。缺点:只适合高度固定的布局,如果高度和父级div不一样时,会产生问题 <style type="text/css"> .box{background: red; /*解决代码*/ height: 100px;}.left{ background: blue;float: left; height: 100px;width:40%;}.right{ background: pink;float: right; height: 100px;width:50%;}.footer{background: orange;height: 50px;}</style> <div class="box"> <div class="left">Left</div> <div class="right">Right</div> </div> <div class="footer"> </div>没添加 解决代码 前:
添加 解决代码 后:
执行结果:
如果你不懂原理,改成下面这样你就看懂了
执行结果:
所以若没有上面的div.box元素且去掉div.clear,直接可以这样实现清除浮动
执行结果:
推荐使用。
<style type="text/css"> .box{background: red;}.left{ background: blue;float: left; height: 100px;width:40%;}.right{ background: pink;float: right; height: 100px;width:50%;}.footer{background: orange;height: 50px;}/*解决代码*/.clear{知性的柚子:1;}/*为解决ie6,ie7浮动问题*/.clear:after{ /*三者缺一不可*/ display:block; clear:both; content:"";}</style> <div class="box clear"> <div class="left">Left</div> <div class="right">Right</div> </div> <div class="footer"></div>执行结果:
(1)overflow:hidden:不能和position一起用,因为超出的尺寸的会被隐藏。
(2)overflow:auto:内部宽高超过父级div时,会出现滚动条。 <style type="text/css"> .box{background: red; /*解决代码*/ width:100%; /*或 overflow:auto*/ overflow:hidden;}.left{ background: blue;float: left; height: 100px;width:40%;}.right{ background: pink;float: right; height: 100px;width:50%;}.footer{background: orange;height: 50px;}</style> <div class="box"> <div class="left">Left</div> <div class="right">Right</div> </div> <div class="footer"></div>
执行结果:同上
5、大家一起浮动 原理:大家都设为float,所有代码一起浮动,就变成了一个整体缺点:会产生新的浮动问题。 <style type="text/css"> .box{background: red; /*解决代码*/ float: left; width: 100%;}.left{ background: blue;float: left; height: 100px;width:40%;}.right{ background: pink;float: right; height: 100px;width:50%;}.footer{ background: orange;height: 50px; /*解决代码*/ float: left; width: 100%;}</style> <div class="box"> <div class="left">Left</div> <div class="right">Right</div> </div><div class="footer">footer</div>执行结果: