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

BFC #2

Open
youyuxun opened this issue May 24, 2018 · 0 comments
Open

BFC #2

youyuxun opened this issue May 24, 2018 · 0 comments

Comments

@youyuxun
Copy link
Owner

BFC

BFC,块格式化上下文文(block formatting context),在面试中经常会碰到这个问题。在这里总结归纳下。

###定义
BFC是在页面渲染时,块级盒布局出现的区域,同时也是浮动元素交互的区域。这样讲其实很晦涩,不妨这样理解:
在一个文档中,如果所有元素都处于文档流中,那他们都属于同一个BFC,可以说它是环境或者属性。但是不代表一个文档里只有一个BFC。

###激活BFC的条件
激活BFC的条件有很多,总结如下:

  1. float属性为leftright
  2. position属性为absolutefixed;
  3. 块容器但不是块级盒模型的元素,简单来说就是display属性为inline-blocktable-celltable-captionflexinline-flex
  4. overflow属性为autoscrollhidden

###BFC的作用
在BFC的布局中,box会紧贴着BFC的左边缘,自上向下排列,即使存在浮动元素,这样就会出现浮动元素覆盖在box上的情况。
利用BFC,我们可以解决很多问题:

  1. 同属于一个BFC时,box垂直方向的距离会由各自的margin值决定,也就是会发生合并情况。解决方法就是将box置于不同的BFC中,这样margin值会分开计算,不会合并

  2. 在BFC中若有浮动元素,就会出现类似文字环绕的情况。这时只要为被覆盖的元素设置一个新的BFC即可解决问题

  3. 高度的塌陷。在一个BFC中,若都为浮动元素,则父元素的高度会塌陷,这时我们就需要为父元素设置BFC,就是常说的清除浮动。关于清除浮动的最佳实践如下:

    .clearfix:before,
    .clearfix:after {
    content: '';
    display: table
    }
    .clearfix:after{
    clear: both
    }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant