首先,我们创建两个盒子,添加浮动做到左边一个右边一个,然后在top之后增加一个bottom块
<head> <style> .box1{ float: left; width: 100px; height: 100px; background-color: tomato; } .box2{ float: right; width: 100px; height: 100px; background-color: yellow; } .bottom{ height: 50px; background-color: springgreen; } </style> </head> <body> <div class="top"> <div class="box1">11111</div> <div class="box2">22222</div>
</div>
<div class="bottom"></div>
</body>
效果图
可以看到bottom到了顶部,而不是top的下面,此时的top高度为0;这是因为有浮动的关系,所以需要清除浮动。
方法1:设置top的高度和内层元素高度一致
.top{ height: 100px; background-color: thistle; }
方法2:overflow: hidden;父级的高度就随子级容器及子级内容的高度而自适应
.top{ overflow: hidden; background-color: thistle; }
效果图
方法3:在top里在添加最后一个块级子元素,设置clear: both;两边都不允许有浮动对象
<head> <style> .box1{ float: left; width: 100px; height: 100px; background-color: tomato; } .box2{ float: right; width: 100px; height: 100px; background-color: yellow; } .box3{ clear: both; } .bottom{ height: 50px; background-color: springgreen; } </style> </head> <body> <div class="top"> <div class="box1 box">11111</div> <div class="box2 box">22222</div> <div class="box3"></div> </div> <div class="bottom"></div> </body>
方法3延伸:运用伪元素,用top::after代替box3,zoom: 1是针对旧版本的
.top::after{
content: "";
display: block;
clear: both;
zoom: 1;
}
整合一下上面的代码,可以单独提出一个用于清除浮动的类clearfix
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> .clearfix::after { content: ''; display: block; clear: both; zoom: 1; } .box1 { float: left; width: 100px; height: 100px; background-color: tomato; } .box2 { float: right; width: 100px; height: 100px; background-color: yellow; } .bottom{ height: 50px; background-color: springgreen; } </style> </head> <body> <div class="top clearfix" > <div class="box1">11111</div> <div class="box2">22222</div> </div> <div class="bottom"></div> </body> </html>
效果图: