BFC(Block Fomatting Context) 块级格式化上下文
- 形成独立的渲染区域,内部元素的渲染不会影响外界
- 作用:
- 消除外边距重叠现象(同一个BFC的两个相邻Box的上下margin会发生重叠)
- 清除浮动(计算BFC的高度时,浮动元素也参与计算)
- 阻止元素被浮动元素覆盖
- 阻止子元素设置margin-top,父元素也一起掉下来
<style> .box1 { margin-top: 300px; height: 600px; background-color: rebeccapurple; } </style> <div class="father"> <div class="box1"></div> </div>
- 自适应两栏布局(左边固定,右边自适应)
- 触发BFC:
- float不为none
- position为absolute或者fixed
- overflow不为visible
- flex元素
- inline-block元素
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
/* 方案一 */
html,
body {
padding: 0;
margin: 0;
height: 100%;
}
.box1 {
float: left;
width: 300px;
height: 100%;
background-color: green;
}
.box2 {
float: left;
width: calc(100% - 300px);
height: 100%;
background-color: blue;
}
/* 方案二: flex布局 */
/* html {
padding: 0;
margin: 0;
height: 100%;
}
body {
padding: 0;
margin: 0;
height: 100%;
display: flex;
flex-direction: row;
}
.box1 {
width: 300px;
height: 100%;
background-color: green;
}
.box2 {
height: 100%;
flex-grow: 1;
background-color: blue;
} */
/* 方案三 触发bfc,但是宽度默认自适应*/
/* html,
body {
padding: 0;
margin: 0;
height: 100%;
}
.box1 {
float: left;
width: 300px;
height: 100%;
background-color: green;
}
.box2 {
overflow: hidden;
height: 100%;
background-color: blue;
} */
</style>
</head>
<body>
<div class="box1"></div>
<div class="box2"></div>
</body>
</html>
清除浮动
- overflow:hidden;
- 内墙法/外墙法
- 伪元素清除
选择器::after{
content:'';
height:0;
clear:both;
display:none;
visibility:none;
overflow:hidden
}