理解BFC是什么,怎么触发,解决了什么问题;
BFC是什么,怎么触发解决了什么问题;
一 css有3种文档流
1 普通流:块独占一行,内联元素在行内
2 定位流
3 浮动流
3种流会相互影响产生问题;可通过BFC(block formatting context,bfc里面的子元素不会对外面的元素产生影响)来解决相关的问题
二 BFC触发条件
1 float不为none
2 overflow不为visible
3 display不为block inline none (为tabale-cell table-caption grid flex inline-block五种之一)
4 position不为static或者relative
5 body本身
三 存在的问题,可以利用bfc解决
1 margin重叠的问题;
解决方案可以分别放在两个具有bfc特性的父元素里面
1 margin塌陷的问题;
解决方式两种
父级bfc,
父级设置边框
3 高度坍塌 当子元素设置float:left|right或者position:absolute;子元素影响了父级元素,子元素脱离了文档流导致父元素高度撑不起来;
可以设置父级元素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>交行面试题验证</title>
<style>
/* marign重合问题 解决 */
.bfc-container{
/*
此处触发的bfc,bfc里面的元素不会对外面的元素产生影响;
*/
overflow: hidden;
}
.box{
width: 100px;
height: 100px;
}
.box1{
background-color: lightcoral;
margin-bottom: 20px;
}
.box2{
background-color: lightgreen;
margin-top:20px;
}
/* margin塌陷问题 解决*/
.box-f{
width: 100px;
height: 100px;
background-color: brown;
/* 下面的不设置会使得整体被顶下去 ,方案一设置父元素bfc*/
/* overflow: hidden;
display: inline-block;
float: left; */
/* 解决方法二,给父元素设置边框 */
border: 1px solid #f00;
}
.box-c{
width: 50px;
height: 50px;
margin-top:50px;
/* margin-left: 50px; // 发现margin-left不会像margin-top一样存在塌陷问题 */
/* 给子元素设置margin-top 直接top在父元素的上层了,就会直接将父元素也顶下去 */
background-color: aquamarine;
}
/* 高度坍塌解决 */
.boxhf{
width: 100px;
background-color: aqua;
border: 1px solid #000;
/* 设置父元素bfc */
position: absolute;
}
.boxhc{
width: 100px;
height: 100px;
background-color:bisque;
float: left;
}
</style>
</head>
<body>
<!-- margin重合问题 -->
<div class="bfc-container">
<div class="box box1"></div>
</div>
<div class="bfc-container">
<div class="box box2"></div>
</div>
--------------
<!-- margin塌陷问题 -->
<div class="box-f">
<div class="box-c"></div>
</div>
---------------
<!-- 高度坍塌 -->
<div class="boxhf">
<div class="boxhc"></div>
</div>
</body>
</html>
浙公网安备 33010602011771号