子元素浮动后父级元素高度自适应高度

来源:互联网 发布:淘宝产品视频制作 编辑:程序博客网 时间:2024/04/30 12:17

正常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> 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

效果图

这里写图片描述

解决方案一:使用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> 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

效果图

这里写图片描述

解决方案二:对父级样式加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> 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

效果图

这里写图片描述

0 0
原创粉丝点击