解决子级用CSS float浮动 而父级div没高度不能自适应高度

来源:互联网 发布:万能网络摄像头客户端 编辑:程序博客网 时间:2024/05/19 10:12

当一个div的子级用了float浮动时,这个div的高度就不受子级div高度的影响了。
如:

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>父div不自适应高度实例</title></head><style> .father { width:500px; border:1px solid #000; padding:10px}.children_1 { width:220px; height:100px; background:#0066CC}.children_2 { width:230px; height:100px; background:#F9F900}.fl { float:left; }.fr { float:right; }</style> <body>    <div class="father">        <div class="children_1 fl"></div>        <div class="children_2 fr"></div>    </div></body></html>

运行结果:
这里写图片描述

这是因为css float的响应,有三种方式可以解决这个问题。

方法一:对父级设置固定高度

此方法可用于能确定父级div内子级对象高度。
假如以上案例,我们知道内部div高度100px,那对父级设置css height为100px看看效果。

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>父div不自适应高度实例</title></head><style> .father { width:500px; border:1px solid #000; padding:10px; height:100px;}.children_1 { width:220px; height:100px; background:#0066CC}.children_2 { width:230px; height:100px; background:#F9F900}.fl { float:left; }.fr { float:right; }</style> <body>    <div class="father">        <div class="children_1 fl"></div>        <div class="children_2 fr"></div>    </div></body></html>

这里写图片描述
此方法缺点,父级是固定高度,而不随内容高度自适应高度,没高度。此方法针对能确定父div内的内容高度情况下使用。

方法二:加css clear解决父div不能自适应高度

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>父div不自适应高度实例</title></head><style> .father { width:500px; border:1px solid #000; padding:10px;}.children_1 { width:220px; height:100px; background:#0066CC}.children_2 { width:230px; height:100px; background:#F9F900}.fl { float:left; }.fr { float:right; }.cb {clear: both;}</style> <body>    <div class="father">        <div class="children_1 fl"></div>        <div class="children_2 fr"></div>        <div class="cb"></div>    </div></body></html>

这里写图片描述
此方法需要注意是clear:both加的位置,不是对父级直接加clear样式,而是在父级前加带clear对象盒子。

方法三:对父级样式加overflow样式

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

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>父div不自适应高度实例</title></head><style> .father { width:500px; border:1px solid #000; padding:10px; overflow:hidden;}.children_1 { width:220px; height:100px; background:#0066CC}.children_2 { width:230px; height:100px; background:#F9F900}.fl { float:left; }.fr { float:right; }</style> <body>    <div class="father">        <div class="children_1 fl"></div>        <div class="children_2 fr"></div>    </div></body></html>

这里写图片描述
推荐。此方法为非常简单解决子用float,父div不能自适应高度,不能随父内容多少而自适应高度没有高度。

0 0