由外边距合并到BFC

时间:2023-03-10 03:05:46
由外边距合并到BFC

置顶文章:《纯CSS打造银色MacBook Air(完整版)》

上一篇:《JavaScript实现Ajax小结》

作者主页:myvin
博主QQ:851399101(点击QQ和博主发起临时会话)

::selection{ background:blue; color:red; } span{ color:red; }


外边距合并

myvin今天主要说的是BFC,块级格式化上下文,这里先由外边距合并引出来。

对于外边距合并,应该都不陌生,在这里简单列出外边距合并的几种情况:

  1. 两个元素上下相邻,则上面元素的下边距会和下面元素的上边距合并,取最大值;
  2. 外部元素包含一个内部元素,外部元素和内部元素的上边距或/和下边距会发生合并;
  3. 自身外边距合并:一个空元素,如果设置了上下外边距,则和合并,即比如,一个空的div,如果上外边距和下外边距都设置为20px,则上下外边距合并为一个,实际的高度为20px。

BFC(块级格式化上下文)

在这里,myvin以第二种情况来引出BFC。

首先给出代码,下面的均已该代码为模型:

<div id="outer">
  <div id="inner">
  </div>
</div>

#outer {
  width:300px;
  height:300px;
  background-color:red;
  margin-top:20px;
}

#inner {
  width:50px;
  height:50px;
  background-color:blue;
  margin-top:10px;
}

这里外部div margin-top:20px,内部div margin-top:10px。

如果将外部div margin-top:10px,内部div margin-top:20px,则两者的效果是一样的,即外部div的margin-top为20px,而内部div紧贴上部。效果如下:

由外边距合并到BFC

也许我们要的效果是外部div距离顶端10px,内部div距离外部div上边界20px,但是如上所述,这样的设置只能得到上面的效果。

到这里,就有必要聊一下BFC了。

BFC可以理解为一种属性,一种状态。

这里先给出w3c官方对BFC的解释,也可点击链接(http://www.w3.org/TR/CSS2/visuren.html#block-formatting)直接查看

Floats, absolutely positioned elements, block containers (such as inline-blocks, table-cells, and table-captions) that are not block boxes, and block boxes with 'overflow' other than 'visible' (except when that value has been propagated to the viewport) establish new block formatting contexts for their contents.

In a block formatting context, boxes are laid out one after the other, vertically, beginning at the top of a containing block. The vertical distance between two sibling boxes is determined by the 'margin' properties. Vertical margins between adjacent block-level boxes in a block formatting context collapse.

In a block formatting context, each box's left outer edge touches the left edge of the containing block (for right-to-left formatting, right edges touch). This is true even in the presence of floats (although a box's line boxes may shrink due to the floats), unless the box establishes a new block formatting context (in which case the box itself may become narrower due to the floats).

英文并不难懂,这里就不再详细翻译。这里主要讲了两点;

  1. 怎样能实现一个BFC
  2. BFC有什么用

我们先说第一点:怎么能够实现一个BFC,如下:

  1. float元素
  2. 绝对定位元素,点出一点,绝对定位元素包括absolute和fixed
  3. display:inline-block,table-cell,table-caption
  4. overflow除了visible的其他属性值。

作用主要是两点:

  1. 在BFC盒子中,两个垂直相邻的元素外边距会发生合并,还有一层意思就是,分别属于两个不同BFC盒子的不会发生合并;
  2. 对浮动也有影响,这也就是为什么设置父元素overflow:hidden能清除浮动的原因。

在这里使用overflow:hidden来设置BFC属性,当然可以用使用fixed、absolute等上述方式。

我们依然尝试实现上面我们没有实现的效果,在这里我们给外部div添加overflow:hidden,使之成为一个具有BFC属性的盒子,现在来看下效果;

由外边距合并到BFC

这样确实实现了所要的效果。

众所周知,如果唯一的一个内部元素是浮动元素,那么父元素是会发生坍塌的,即父元素无法被撑起来,如果将BFC设置到父元素上,父元素会被浮动元素正常撑起来,清除浮动。

所以,设置BFC就相当于设置了一个和外部隔离的独立环境,在这个环境里,浮动元素正常撑起父元素;如果A设置了BFC,B设置了BFC,B中有元素B1,A中有元素A1,则分别设置A1和B1的外边距的话,它们是不会合并的,因为这时候它们的外边距是相对于自己的父元素的。


转载请记得说明作者和出处哦-.-
作者:myvin
原文出处:http://www.cnblogs.com/myvin/p/4892545.html


下一篇:《图片ping、JSONP和CORS跨域 》

置顶文章:《纯CSS打造银色MacBook Air(完整版)》