標籤:

body上加上overflow:hidden為什麼沒形成BFC阻止body下移?

http://codepen.io/agileago/pen/QbeyXg

做了一個例子,起初body上沒加overflow:hidden導致第一個fixed的div下移就很奇怪,後來想通了是因為第二個div有margin導致body下移所以第一個div也就下移了,但是body上加上overflow:hidden了,為什麼沒有阻止body下移?這個始終沒想通


瀉藥

這是個難說的問題

幾乎沒有CSS方面的官方規範來說這個事情

官方的表示是

"propagated to the viewport"

這個情況下需要特殊看待

首先,body 的確是下移了

對 @於江水 的方式加以修改

設置的背景色其實傳播到視口了(propagated to the viewport)

這種傳播的情況還有一些

比如滾動條

現在的html body

都是 overflow visible 的

但是視口高小於300 時候 依然會有滾動條

這時候這個滾動條是視口給的不屬於 html 和 body

但是

你給他們任意設置一個scroll

不會出現雙滾動或多滾動條

它們的設置也被傳播到視口了

只有它們同時都設置 scroll

視口的 scroll 才無效

也就是說這樣阻止了傳播

把問題拉回來到BFC上來

規範是這麼寫的

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.

不是visible (除非該值已經傳播到視口)建立新BFC

看起來 body上加上overflow:hidden 這個值傳播到視口了

所以符合了除非內的規則

沒有建立BFC

你可以試試看 float、nline-blocks, table-cells, table-captions 這些

BFC可以建立

間隙消失

(這些可能會導致shrink-to-fit,記得給個width)


因為你設置在 body 上的 overflow 被應用到 viewport 上了。

Visual effects:

UAs must apply the "overflow" property set on the root element to the viewport. When the root element is an HTML "HTML" element or an XHTML "html" element, and that element has an HTML "BODY" element or an XHTML "body" element as a child, user agents must instead apply the "overflow" property from the first such child element to the viewport, if the value on the root element is "visible". The "visible" value when used for the viewport must be interpreted as "auto". The element from which the value is propagated must have a used value for "overflow" of "visible".

segmentfault 上有討論過這個問題,就不搬運了:

重提CSS中外邊距摺疊問題

例子修改後: http://codepen.io/anon/pen/vOoPEx


body上沒加overflow:hidden導致第一個fixed的div下移就很奇怪

----------------

要是我的話,肯定給fixed的div加上top:0;完事。當然也不會想到這麼深的事情。

從來沒有給body加過ov:h;

看了莫大的回答,表示之前看的BFC教程,都把expect去除了,坑啊。


推薦閱讀:

margin-right值的計算疑惑?
a:link/a:visited 為什麼優先順序比class高?
到底該不該用 CSS reset?
line-height:normal是怎樣計算的?
全局樣式加 float:left 導致 div{margin:0 auto;} 不起作用,為什麼?

TAG:CSS | 布局 |