1.BFC概念
BFC(Block Formatting Contexts)块级格式化上下文,它是页面中的一块渲染区域,并且有一套渲染规则,它决定了其子元素将如何定位,以及和其他元素的关系和相互作用。
具有BFC特性的容器会隔离外界的一切,无论外面的元素如何变化都始终不会影响内部。
2.BFC触发条件
- float的值不是none
- position的值不是static或是relative
- display的值是inline-block、table-cell、flex、table-caption或者inline-flex
- overflow的值不是默认值visible
3.BFC典型应用
-
解决margin传递
比如给子元素设置margin-top,但是父元素也会受到影响。如果启动BFC就能够很好地解决该问题,使得无论内部元素如何改变都不会影响外部
<!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>
.main{
width: 200px;
height: 200px;
background-color: aqua;
/* 触发Bfc */
float: left;
}
.main div{
width: 100px;
height: 100px;
background-color: salmon;
margin-top: 30px;
}
</style>
</head>
<body>
<div class="main">
<div></div>
</div>
</body>
</html>
-
解决margin折叠
两个div元素要各自启动BFC
<!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>
section{
overflow: hidden;
}
.div1{
width: 100px;
height: 100px;
background-color: aqua;
margin-bottom: 20px;
}
.div2{
width: 100px;
height: 200px;
background-color: pink;
margin-top: 20px;
}
</style>
</head>
<body>
<section>
<div class="div1"></div>
</section>
<section>
<div class="div2"></div>
</section>
</body>
</html>
-
解决父容器高度塌陷问题
子元素设置浮动后,父容器容易出现高度塌陷的问题。
<!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>
.main{
/* 触发BFC */
width: 100px;
overflow: hidden;
border: 1px solid black;
}
.main div {
width: 100px;
height: 100px;
float: left;
background-color: aqua;
}
</style>
</head>
<body>
<div class="main">
<div></div>
</div>
</body>
</html>