学习CSS中的BFC

定义

BFC全称为block formatting context,意为块级格式化上下文,是Web页面中盒模型布局的css渲染模式。css

可能上面的解释看了有点懵逼,通俗的说BFC指的的是一块区域的布局, 这个区域的布局有一个显著特色:这个区域内的子元素不管使用何种布局、何种样式都不会影响外部的元素。BFC比较常见的用法就是用来清除浮动的影响,正常不清楚浮动影响的状况下,父元素的高度是会坍塌的html

那么何时会触发BFC呢?知足一下条件中任何一个:布局

  • float的值不为none
  • position的值不为static或者relate
  • display的值为table-cell、table-caption、inline-block、flex或者inline-flex中的任意一个
  • overflow的值不为visible

做用

清除浮动

咱们常常会遇到这样的状况:当一个容器内包含的子元素包含浮动元素时,会致使容器没有高度,人们经常使用一个伪类,而后在伪类中用clear属性清除浮动,其实能够经过定义一个BFC来达到一样的目的,举个例子:flex

<div class="container">
    <div></div>
    <div></div>
</div>
.container {
  width: 600px;
  background-color: black;
}
.container div {
  float: left;
  width: 200px;
  height: 200px;
  margin-left: 10px;
  background-color: green;
}

clipboard.png

当子元素存在float属性时,父容器没有设置高度,父容器的高度就会塌陷,咱们能够经过在父容器中加overflow:hidden建立一个BFC来解决这个问题:阿里云

.container {
  width: 600px;
  background-color: black;
  overflow: hidden;  
}
.container div {
  float: left;
  width: 200px;
  height: 200px;
  margin-left: 10px;
  background-color: green;
}

clipboard.png

防止文字环绕

<div>
    <img src="../public/image/test.jpeg">
    <p>test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test </p>
</div>
img {
  float: left;
  width: 40px;
  height: 40px;
}

clipboard.png

如上面例子所示,正常状况下咱们期待的结果是左边显示图片,右边显示文字描述,而不是上面展现的文字环绕在图片周围,此时咱们一样能够经过建立一个BFC来解决这个问题:spa

img {
  float: left;
  width: 40px;
  height: 40px;
  margin-right: 10px;
}
p {
  overflow: hidden;
}

防止外边距折叠

常规文档流中,子元素都是沿着父元素顶部开始一个接着一个垂直摆放的,相邻兄弟间的垂直间距由他们中间距最大的一个元素决定,而不是叠加在一块儿,这就是边距折叠,举个例子:code

<div class="container">
    <p class="one">one</p>
    <p class="two">two</p>
</div>
.container {
  width: 200px;
  background-color: black;
}
p {
  width: 150px;
  background-color: green;
}
.one {
  margin: 10px 0;
}
.two {
  margin: 20px 0;
}

clipboard.png

这种状况,咱们能够经过建立一个新的BFC来解决orm

<div class="container">
  <p class="one">one</p>
  <div class="new">
    <p class="two">two</p>
  </div>
</div>
.container {
  width: 200px;
  background-color: black;
}
p {
  width: 150px;
  background-color: green;
}
.one {
  margin: 10px 0;
}
.two {
  margin: 20px 0;
}
.new {
  overflow: hidden;
}

clipboard.png

总结

这篇文章简单的介绍了BFC特色和举例了BFC的经常使用方法,若是有错误或不严谨的地方,欢迎批评指正,若是喜欢,欢迎点赞收藏
最后,打个小广告:阿里云双十一云服务新用户一折优惠车票htm

相关文章
相关标签/搜索