1 给浮动元素的父元素设置高度,只适合高度固定的布局,要给出精确的高度,如果高度和父级div不一样时,会产生问题。
<style type="text/css"> .div1{background:#000080;border:1px solid red;/*解决代码*/height:200px;} .div2{background:#800080;border:1px solid red;height:100px;margin-top:10px} .left{float:left;width:20%;height:200px;background:#DDD} .right{float:right;width:30%;height:80px;background:#DDD} </style> <div class="div1"> <div class="left">Left</div> <div class="right">Right</div> </div> <div class="div2"> div2 </div>
2 在浮动元素后加一个空div,给div设置css属性:clear: both; 让父级div能自动获取到高度,浏览器支持好,如果页面浮动布局多,就要增加很多空div,让人感觉很不好。
<html>, <head> <script type="text/javascript" src="jquery.js"></script> <style type="text/css"> .div1{ background:#000080; border:1px solid red; } .div2{ background:#800080; border:1px solid red; height:100px; margin-top:10px } .left{ float:left; width:20%; height:200px; background:#DDD } .right{ float:right; width:30%; height:80px; background:#DDD } /*解决代码*/ .clearfloat{clear:both} </style> </head> <body> <div class="div1"> <div class="left">Left</div> <div class="right">Right</div> <!-- 解决代码 --> <div class="clearfloat"></div> </div> <div class="div2"> div2 </div> </body> </html>
3 IE8以上和非IE浏览器才支持:after,zoom(IE转有属性)可解决ie6,ie7浮动问题
<html> <head> <script type="text/javascript" src="jquery.js"></script> <style type="text/css"> .div1{ background:#000080; border:1px solid red; } .div2{ background:#800080; border:1px solid red; height:100px; margin-top:10px } .left{ float:left; width:20%; height:200px; background:#DDD } .right{ float:right; width:30%; height:80px; background:#DDD } /*清除浮动代码*/ .clearfloat:after{ display:block; clear:both; content:""; visibility:hidden; height:0 } .clearfloat{ zoom:1 } </style> </head> <body> <div class="div1 clearfloat"> <div class="left">Left</div> <div class="right">Right</div> </div> <div class="div2"> div2 </div> </body> </html>
4 给父元素添加overflow:hidden
<html> <head> <script type="text/javascript" src="jquery.js"></script> <style type="text/css"> .div1{ background:#000080; border:1px solid red; /*解决代码*/ overflow: hidden; } .div2{ background:#800080; border:1px solid red; height:100px; margin-top:10px } .left{ float:left; width:20%; height:200px; background:#DDD } .right{ float:right; width:30%; height:80px; background:#DDD } </style> </head> <body> <div class="div1"> <div class="left">Left</div> <div class="right">Right</div> </div> <div class="div2"> div2 </div> </body> </html>