Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

【CSS】题7. 说说对BFC规范的理解 #13

Open
Easay opened this issue Apr 4, 2021 · 0 comments
Open

【CSS】题7. 说说对BFC规范的理解 #13

Easay opened this issue Apr 4, 2021 · 0 comments
Labels

Comments

@Easay
Copy link
Owner

Easay commented Apr 4, 2021

1.什么是BFC

当元素在页面上垂直或水平排布时,它们之间如何相互影响,CSS有几套不同的规则,其中一套叫块级格式化上下文(Block Formatting Context)。

  • 格式化上下文
    Formatting context 是 W3C CSS2.1 规范中的一个概念。它是页面中的一块渲染区域,并且有一套渲染规则,它决定了其子元素将如何定位,以及和其他元素的关系和相互作用。最常见的 Formatting context 有 Block fomatting context (简称BFC)和 Inline formatting context (简称IFC)。

BFC是一个独立的布局环境,其中的元素布局是不受外界的影响,并且在一个BFC中,块盒与行盒(行盒由一行中所有的内联元素所组成)都会垂直的沿着其父元素的边框排列。

2.如何创建BFC

  • 根元素,即html元素;
  • display的值是 inline-block | table-cell | flex | table-caption | inline-flex的;
  • float的属性值不是none的元素;
  • 绝对定位、固定定位的元素;
  • overflow属性值不是visible的元素。

3.BFC的特性

  • 内部的盒子会在垂直方向上一个接一个放置
  • Box垂直方向的距离由margin决定。属于同一个BFC的两个相邻Box的margin会发生重叠。
  • 每个盒子(块盒与行盒)的margin box的左边,与包含块border box的左边相接触(对于从左往右的格式化,否则相反)。即使存在浮动也是如此。
  • BFC的区域不会与float的元素区域重叠
  • 计算BFC的高度时,浮动子元素也参与计算
  • BFC就是页面上的一个隔离的独立容器,容器里面的子元素不会影响到外面的元素,反之亦然

4.BFC的作用

  • 阻止margin重叠
<style>
 p {
        color: #f55;
        background: yellow;
        width: 200px;
        line-height: 100px;
        text-align:center;
        margin: 30px;
    }
</style>
<body>
    <p>看看我的 margin是多少</p>
    <p>看看我的 margin是多少</p>
</body>

由于发生margin折叠,所有两个p之间的margin只有30,而不是60。
可以通过将第二个p放入div中,并给div设置BFC

<style>
div{
        overflow: hidden;
    }
</style>
<body>
    <p>看看我的 margin是多少</p>
    <div>
        <p>看看我的 margin是多少</p>
    </div>
</body>
  • 自适应多栏布局
    与浮动元素相邻的已生成BFC的元素不能与浮动元素互相覆盖。利用该特性可以作为多栏布局的一种实现方式. 特点在于左右俩栏的宽度固定,中间栏可以根据浏览器宽度自适应
  • 解决浮动元素使父元素高度塌陷的问题
    常见的方式是为父元素设置overflow:hidden或者浮动父元素。根本原因在于创建BFC的元素,子浮动元素也会参与其高度计算。
@Easay Easay added the CSS label Apr 4, 2021
@Easay Easay changed the title 【CSS】题7.说说对BFC规范的理解 【CSS】题7. 说说对BFC规范的理解 Apr 4, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant