1. 为什么需要清除浮动?
由于父级盒子在很多情况下,不方便给高度,但是子盒子浮动又不占有位置,就会影响下面的标准流盒子(标准流盒子上移)。
2. 清除浮动的本质
清除浮动的本质是清除浮动元素造成的影响:浮动的子标签无法撑开父盒子的高度
- 如果父盒子本身有高度,则不需要清除浮动
- 清除浮动之后,父级就会根据浮动的子盒子自动检测高度
- 父级有了高度,就不会影响下面的标准流了
3.实现
- 给父元素添加高度
.father {
width: 200px;
height: 300px;
border: 1px solid red;
}
.big {
width: 100px;
height: 100px;
background-color: green;
float: left;
}
.small {
width: 50px;
height: 50px;
background-color: yellow;
float: left;
}
.footer {
width: 200px;
height: 100px;
background-color: blue;
}
</style>
</head>
<body>
<div class="father">
<div class="big">big</div>
<div class="small">small</div>
</div>
<div class="footer"></div>
</body>
2. 给父级元素设置overflow:hidden不推荐
内容增多的时候容易造成不会自动换行导致内容被隐藏掉,无法显示要溢出的元素
<style>
.father {
width: 200px;
height: 250px;
border: 1px solid red;
overflow: hidden;
}
.big {
width: 100px;
height: 100px;
background-color: green;
float: left;
}
.small {
width: 50px;
height: 50px;
background-color: yellow;
float: left;
}
.footer {
width: 200px;
height: 100px;
background-color: blue;
}
</style>
</head>
<body>
<div class="father">
<div class="big">big</div>
<div class="small">small</div>
</div>
<div class="footer"></div>
</body>
- 额外标签法(在子元素后面追加一个空白标签)
不推荐
添加无意义标签,语义化差
.father {
border: 1px solid red;
}
.big {
width: 100px;
height: 100px;
background-color: green;
float: left;
}
.small {
width: 50px;
height: 50px;
background-color: yellow;
float: left;
}
.footer {
width: 200px;
height: 100px;
background-color: blue;
}
.clear {
clear: both;
}
</style>
</head>
<body>
<div class="father">
<div class="big">big</div>
<div class="small">small</div>
<div class="clear">额外标签法</div>
</div>
<div class="footer"></div>
</body>
4. 父级添加after伪元素推荐
伪元素是行内元素 正常浏览器清除浮动方法
<style>
.father {
width: 200px;
height: 250px;
border: 1px solid red;
}
.clear:after {
content: "";
display: block;
height: 0;
clear: both;
visibility: hidden;
}
.clear {
zoom: 1;
/* 兼容ie6-7 */
}
.father .big {
width: 100px;
height: 100px;
background-color: green;
float: left;
}
.small {
width: 50px;
height: 50px;
background-color: yellow;
float: left;
}
.footer {
width: 200px;
height: 100px;
background-color: blue;
}
</style>
</head>
<body>
<div class="father clear">
<div class="big">big</div>
<div class="small">small</div>
</div>
<div class="footer"></div>
</body>
- 父级添加双伪元素
推荐
<style>
.father {
width: 200px;
height: 250px;
border: 1px solid red;
}
.clear:before,
.clear:after {
content: "";
display: table;
}
.clear:after {
clear: both;
}
.clear {
zoom: 1; /* 兼容ie6-7 */
}
.father .big {
width: 100px;
height: 100px;
background-color: green;
float: left;
}
.small {
width: 50px;
height: 50px;
background-color: yellow;
float: left;
}
.footer {
width: 200px;
height: 100px;
background-color: blue;
}
</style>
</head>
<body>
<div class="father clear">
<div class="big">big</div>
<div class="small">small</div>
</div>
<div class="footer"></div>
</body>
总结
- 给父级设置高度height
- 结尾处添加一个空白div标签设置clear:both
- 父级定义伪类:after和zoom
- 父级定义overflow:hidden
- 父级也浮动,但是需要定义宽度