CSS-块格式化上下文

CSS-块格式化上下文

1. 概述

​ 块格式化上下文(Block Formattiong Context, 简称BFC) 是Web页面的可视化CSS渲染的一部分,是块盒子的布局过程发生的区域,也是浮动元素与其他元素交互的区域。

​ 一个独立的BFC会包含所有内部的子元素,不会影响其他元素的布局和交互。

​ 基于同一个BFC内的子元素,子元素两者间会发生外边距上下折叠情况,避免此情况的其中一个方法是子元素间的其中一个设置为BFC且子元素的内部元素再设置外边距。

2. 可创建为BFC的属性:

1. 根元素(<html>)
2. 浮动元素({ float: 非none })
3. 绝对定位元素({ position: absolute|fixed })
4. 行内块元素({ display: inline-block })
5. 表格单元格({ display: table-cell })
6. 表格标题({ display: table-caption })
7. 匿名表格单元格元素
8. overflow值不为visible的块元素({ overflow: 非visible })
9. display值为flow-root的元素(flow-root可理解为类似html根元素的上下文,无副作用,首选)({ display: flow-root })
10. contain值为layout、content或paint的元素({ contain: layout|content|paint })
11. 弹性元素({ display: flex|inline-flex })
12. 网格元素({ display: grid|inline-grid})
13. 多列容器(未求证,慎用)

3. 范例

3.1 父级包含浮动元素,不发生穿出父级底部问题

css代码

* {
  margin: 0;
  padding: 0;
}
.container {
  border: 5px solid red;
  /* float: left; */
  /* position: absolute; */
  /* position: fixed; */
  /* display: inline-block; */
  /* display: table-cell; */
  /* display: table-caption; table相关的都可以 */
  /* overflow: hidden; 非visible都可以 */
  /* display: flow-root; 流根(类似与html根元素上下文) */
  /* contain: layout; layout|content|paint 都可以 */
  /* display: flex; */
  /* display: inline-flex; */
  /* display: grid; */
  /* display: inline-grid; */
  display: flow-root;  /* 无副作用,首选 */
}
.float {
  float: left;
  background-color: cornflowerblue;
  color: black;
  font-size: 20px;
  height: 200px;
}
.normal {
  background-color: blueviolet;
}

html代码

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>块格式化上下文</title>
</head>

<body>
    
    <div class="container">
        <div class="float">这是一个浮动元素</div>
        <p class="normal">This is a right normal text.</p>
    </div>

</body>

</html>
3.2 外边距折叠问题

css代码

* {
  margin: 0;
  padding: 0;
}
.a {
  margin-bottom: 20px;
  background: lightcoral;
}
.b {
  margin-top: 20px;
  background: khaki;
}
.b-box {
  display: flow-root;
}

html代码

	<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>块格式化上下文</title>
</head>

<body>
    
    <div class="a">元素A</div>
    <div class="b-box">
        <div class="b">元素B</div>
    </div>

</body>

</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值