CSS清除浮动
一、设置父级元素overflow:hidden 触发BFC使父级元素自适应为子元素的高度
( BFC定义:
BFC(Block formatting context)直译为"块级格式化上下文"。它是一个独立的渲染区域,只有Block-level box参与, 它规定了内部的Block-level Box如何布局,并且与 这个区域 外部毫不相干。)
eg:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>overflow</title>
<style>
.wrap{
width: 400px;
height: 400px;
background-color: blue;
overflow: hidden;
}
.parent{
width: 250px;
height: 200px;
background-color: red;
float: left;
}
.children{
width: 150px;
height: 200px;
background-color: green;
float: left;
}
</style>
</head>
<body>
<div class="wrap">
<div class="parent">子元素一</div>
<div class="children">子元素二</div>
</div>
</body>
</html>
二、在浮动元素之后增加一个没有实际作用的元素代替实际的元素替代浮动元素之后的元素受到浮动的影响
eg:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>clear</title>
<style>
.wrap{
width: 400px;
height: 400px;
background-color: blue;
}
.parent{
width: 250px;
height: 200px;
background-color: red;
float: left;
}
.children{
width: 150px;
height: 200px;
background-color: green;
float: left;
}
.clear{
clear: both;
}
</style>
</head>
<body>
<div class="wrap">
<div class="parent">子元素一</div>
<div class="children">子元素二</div>
<div class="clear"></div>
</div>
</body>
</html>
三、clearfix + after伪元素 方式
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>clearfix</title>
<style>
.wrap{
width: 400px;
height: 400px;
background-color: blue;
}
.parent{
width: 250px;
height: 200px;
background-color: red;
float: left;
}
.children{
width: 150px;
height: 200px;
background-color: green;
float: left;
}
.clearfix:after {
content: "";
display: block;
height: 0;
visibility: hidden;
clear: both;
}
</style>
</head>
<body>
<div class="wrap clearfix">
<div class="parent">子元素一</div>
<div class="children">子元素二</div>
</div>
</body>
</html>