由于盒子模型在WEB开发的布局中经常用到. 在用到盒子模型设计布局的时候,经常会用到float 也就是浮动.
使用浮动后带了很多影响.
请看代码
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<title>Bootstrap</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta charset='utf-8'>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<style>
.box1 {
height: 200px;
width: 200px;
background: red;
float: left;
}
.box2 {
height: 200px;
width: 200px;
background: yellow;
}
.box3 {
width: 600px;
background: green;
}
</style>
</head>
<body>
<div class="box1"></div>
<div class="box2"></div>
</body>
</html>
上面就这个我们定义了2个盒子, 可是不是我们希望的2个盒子并排的显示在一行,而是只看到一个红色的盒子, 因为第一个盒子使用了浮动, 第二个盒子没有 还是标准的文档流这样被浮动的盒子给覆盖了..
解决的办法是 1.给box2 的CSS 里添加 float: left
2.给box2的CSS里添加overflow: hidden;
3.浮动元素后添加这句
<div style="clear:both;"></div>
下面说带有父元素的情况请看代码
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<title>Bootstrap</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta charset='utf-8'>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<style>
.box1 {
height: 200px;
width: 200px;
background: red;
float: left;
}
.box2 {
height: 200px;
width: 200px;
background: yellow;
float: left;
}
.box3 {
width: 600px;
background: green;
}
</style>
</head>
<body>
<h1>Hello, world!</h1>
<div class="box3 clearfix">
<div class="box1"></div>
<div class="box2"></div>
</div>
</body>
</html>
我们希望的是box3 包括了1 2 2个盒子 因为box3没有设置高度那么..作为父元素会被子元素撑开,但是根本不是预想的,
原因就是 子元素带有浮动那么..父元素受到了影响, 导致高度塌陷, 解决办法
1.给box3添加 float:left;
2.给box3添加 overflow:hidden;
3.父元素设置display: table;
4.
<style>
.box1 {
height: 200px;
width: 200px;
background: red;
float: left;
}
.box2 {
height: 200px;
width: 200px;
background: yellow;
float: left;
}
.box3 {
width: 600px;
background: green;
}
.clearfix:after {
content: ".";
display: block;
height: 0;
clear: both;
visibility: hidden;
}
.clearfix {
display: inline-block;
}
/* for IE/Mac */
</style>
<!--[if IE]> <style type="text/css">
.clearfix {zoom: 1;/* triggers hasLayout */
display: block;/* resets display for IE/Win */}
</style>
<![endif]-->
结束. 这些办法 建议使用最后一种这样 就省的每天都要清除了. 只要在需要清除的父元素 添加一个类 clearfix就OK
希望能帮助到大家.