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 知识整理 #6

Open
theydy opened this issue Dec 13, 2018 · 0 comments
Open

BFC 知识整理 #6

theydy opened this issue Dec 13, 2018 · 0 comments

Comments

@theydy
Copy link
Owner

theydy commented Dec 13, 2018

BFC 知识整理

BFC 概念

BFC (块级格式化上下文)

BFC 如何创建

  • float 的值不为 none
  • position 的值不为 static 或者 relative
  • overflow 的值不为 visible
  • display 的值为 table-cell, table-caption, inline-block, flex, inline-flex

BFC 的原理(渲染规则)

  • BFC 内部的Box会在垂直方向上一个接一个的放置
  • BFC 导致垂直方向发生边距重叠,同时BFC 也是解决边距重叠的方案
  • BFC 区域不会与浮动元素的box 重叠,所以可以使用BFC 来清除浮动
  • BFC 内部每个元素的左外边距与包含块的左边界相接触(从右到左的格式化时,则为右边框紧挨),即使浮动元素也是如此,除非这个盒子的内部创建了一个新的 BFC
  • BFC 在页面上是一个独立的容器,外面的元素不会影响BFC 内的元素,同时BFC 内部的元素也不会影响外面的元素
  • BFC 计算高度时,浮动元素也参与计算

BFC 的应用

防止文字环绕 (不和浮动元素重叠)

CodePan查看效果

如果一个浮动元素后面跟着一个非浮动的元素,那么就会产生一个覆盖的现象,这时候在非浮动元素上添加文字,文字会环绕浮动元素。防止文字环绕也就是利用BFC 使非浮动元素与浮动元素不重叠。

<div class="eg eg-1">
  <div class="aside"></div>
  <div class="main">
  Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
  </div>
</div>
// stylus
.eg-1
  width 300px
  position relative
  .aside
    width 100px
    height 150px
    float left
    background #f66
  .main
    height 200px
    background #fcc
    overflow hidden // 生成 bfc

当触发main生成BFC后,这个新的BFC不会与浮动的aside重叠,文字环绕的效果也消失了。main会根据包含块的宽度,和aside的宽度,自动变窄。

清除元素内部浮动 (计算浮动子元素高度)

CodePan查看效果

<div class="eg eg-2">
  <div class="par">
    <div class="child"></div>
    <div class="child"></div>
  </div>
</div>
// stylus
.par
  border 5px solid #fcc
  width 300px
  overflow hidden // 生成BFC
  .child
    border 5px solid #f66
    width 100px
    height 100px
    float left

触发par生成BFC,那么par在计算高度时,par内部的浮动元素child也会参与计算。

防止垂直 margin 重叠

CodePan查看效果

<div class="eg eg-3">
  <p class="p">第一个P</p>
  <div class="bfc-wrap">
    <p class="p">第二个P</p>
  </div>
</div>
// stylus
.p
  color #f55
  background #fcc
  width 200px
  line-height 100px
  text-align center
  margin 20px
.bfc-wrap
  overflow hidden // 生成BFC

同属于一个BFC时,两个元素发生垂直margin重叠,包括相邻元素,嵌套元素,只要他们之间没有阻挡,因此使用一个wrap 包裹住第二个p 元素并生成BFC ,此时两个P 元素不属于同一个BFC ,消除margin 重叠。

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

No branches or pull requests

1 participant