解决子元素用css float浮动后父级元素高度自适应高度

来源:互联网 发布:百度数据分析工具 编辑:程序博客网 时间:2024/04/20 03:11

解决子元素用css float浮动后父级元素高度自适应高度


正常HTML

当在对象内的盒子使用了float后,导致对象本身不能被撑开自适应高度,这个是由于浮动产生原因。

HTML代码

<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>父div不自适应高度实例</title> <style> .divcss5{ width:500px; border:1px solid #000; padding:10px} .divcss5-lf{ float:left; width:220px; height:100px; background:#000} .divcss5-rt{ float:right; width:230px; height:100px; background:#06F} </style> </head> <body> <div class="divcss5"> <div class="divcss5-lf"></div> <div class="divcss5-rt"></div> </div> </body> </html> 

效果图

这里写图片描述

解决方案一:使用css clear清除浮动

对父级div标签闭合前加一个clear清除浮动对象。

HTML代码

<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>父div不自适应高度实例</title> <style> .divcss5{width:500px;border:1px solid #000;padding:10px} .divcss5-lf{ float:left; width:220px; height:100px; background:#000} .divcss5-rt{ float:right; width:230px; height:100px; background:#06F} .clear{ clear:both} </style> </head> <body> <div class="divcss5"> <div class="divcss5-lf"></div> <div class="divcss5-rt"></div> <div class="clear"></div> </div> </body> </html> 

效果图

这里写图片描述

解决方案二:对父级样式加overflow样式

此方法非常简单,也可以作为推荐解决父级不能被撑开自适应高度的方法,可以不增加div盒子对象,只需要对父级加一个overflow:hidden样式即可。

HTML代码

<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>父div不自适应高度实例</title> <style> .divcss5{width:500px;border:1px solid #000;padding:10px; overflow:hidden } .divcss5-lf{ float:left; width:220px; height:100px; background:#000} .divcss5-rt{ float:right; width:230px; height:100px; background:#06F} </style> </head> <body> <div class="divcss5"> <div class="divcss5-lf"></div> <div class="divcss5-rt"></div> </div> </body> </html> 

效果图

这里写图片描述

0 0