边距合并和BFC

2016-07-23  本文已影响11人  NSO

首先明确边距合并是个什么问题。
举例说明:


什么叫边距合并

总结边距合并的三种情况(上图都已经有体现了):


题外话:为什么发生边距合并?

首先要明白html最初设计目的是和一个文本文档一样,默认也是大家在里面写文章放图片,那么自然要换行,所以这个margin就是控制行间距的。自然很多情况下要智能地边距合并才能符合使用者的本意。所以不要怪罪浏览器的解析方式。

不感兴趣的就只看这句话:边距合并是个排版问题。

好了,重点是怎么解决边距合并问题。
比较通用的方法是使用BFC。解释一下BFC是啥:
BFC是块级元素自身形成独立的上下文排版的方式,形成BFC后外部floating、clear这些排版就失效了,BFC内部自己形成一个内部空间
形成BFC的方式,为了防止误解直接给出MDN上的原文:

A block formatting context is created by one of the following:

  1. the root element or something that contains it
  2. floats (elements where float is not none)
  3. absolutely positioned elements (elements where position is absolute or fixed)
  4. inline-blocks (elements with display: inline-block)
  5. table cells (elements with display: table-cell, which is the default for HTML table cells)
  6. table captions (elements with display: table-caption, which is the default for HTML table captions)
  7. elements where overflow has a value other than visible
  8. flex boxes (elements with display: flex or inline-flex)

言归正传,我们解决边距合并问题不是用上面随便一条形成bfc就可以的。比如第1条,稍微思考一下就知道和解决我们的问题没关系。靠谱的是我们利用overflow设置一个属性(当然不能设置visiable上面已经说了)。
要说明三个重要问题:

上一篇 下一篇

猜你喜欢

热点阅读