用 after 清除浮動, before 處理 Margin Collpase 怎麼理解?

時間 2021-06-08 03:15:51

1樓:蔫壞損

Margin collapsing occurs in three basic cases:

Adjacent siblings

The margins of adjacent siblings are collapsed (except when the later sibling needs to be cleared past floats). For example:The bottom margin of this paragraph is collapsed...

...with the top margin of this paragraph.

Parent and first/last child

If there is no border, padding, inline content, or clearance

to separate the margin-top of a block with the margin-top of its first child block, or no border, padding, inline content, height, min-height, or max-height to separate the margin-bottom of a block with the margin-bottom of its last child, then those margins collapse. The collapsed margin ends up outside the parent.

Empty blocks

If there is no border, padding, inline content, height, or min-height to separate a block's margin-top from its margin-bottom, then its top and bottom margins collapse.Margins of floating and absolutely positioned elements never collapse.

引自MDN, 描述了會發生margin collaspe的三種基本情況。注意第二種情況,其實不太嚴謹,w3上的說法是第乙個first in-flow child,而不是單純的first child。如果父元素的margin-top和子元素的margin-top沒有border,padding之類的分隔,子元素和父元素的margin-top發生摺疊,注意第二條結尾,摺疊的外邊距會跑到父元素外面。

此外,浮動元素不會發生外邊距摺疊。

拿你給的鏈結上例子來說

Sibling

demoB-float

demoC

Sibling

結果如圖,demoC是第乙個in-flow的child,demoC和父元素demoA的margin-top摺疊,同時摺疊的外間距跑到了父元素外面。再結合MDN的第一條,相鄰塊狀元素的margin會摺疊,所以demoA+demoC的margin-top和demoE(第乙個sibling) 的margin-bottom摺疊了,最後的margin等於最大的那個margin, 這裡就是demoC的margin-top。

根據MDN第二條,demoA和demoC的margin-top沒被分隔,因此出現了上面的情況。例如,我們給demoA加個padding-top來分割,

.demoA

結果如下

demoC的margin-top回到了父元素內。所以clearfix的原理類似,clearfix:before內的display:

table建立了BFC,從而分隔了父元素demoA和子元素demoC的margin-top,於是就消除了margin collapse。

最後,如果你明白的話就知道你鏈結裡的那個解釋是錯的,首先,float建立了BFC,但是和例子中的margin collapse沒關係,w3中有提到

Two margins are adjoining if and only if:

both belong to in-flow block-level boxes that participate in the same block formatting context

在同一BFC內的in-flow塊狀元素間才會發生margin collapse,float元素是不會發生margin collapse的。此外,例子中clearfix是給demoA的,所以clearfix:before清除的margin collapse不是demoE和demoC的,而是demoC和demoA的。

如果你給demoA也加上margin-top的話,demoE和demoA依然會發生margin collapse。

更多詳情,移步

Mastering margin collapsing

Visual formatting model

Box model

A用免費得來的電影券請B看電影,B是否應該花錢還A這個人情?

wfygqd 這個簡單嘛你也到哪弄一張優惠卷電影也好餐卷也好請回他不就沒問題了嗎?不用太放在心上。當然朋友之間快樂是互相的在她身邊你要真的覺得開心而不是你覺得你應該開心 海哲言 首先,我絕對不信A得到電影券什麼都沒有付出,就算是天上掉餡餅砸中了A,那他也付出了當時的運氣吧!不是只有付出錢才叫有了付出...

請問我用理膚泉b5的方式對嗎。

wang fianna 我屬於反覆起痘的,用過的祛痘產品都是理膚泉,朋友推薦我用的,最開始是k 用了一段時間確實挺有用,效果很明顯,不過用半年左右就像耐藥了一樣,就停用了。後面又冒閉口痘了,看不少說B5修復能力超級強,於是當天就去買了一支。白天回宿舍洗完臉就厚厚的敷了一層等晚上洗臉時洗掉繼續用了平常...

10600kf比10400f貴300,用B460主機板上10600kf划算嗎?

Smoven 不划算,對實際體驗沒有任何幫助的配置,多一分都是浪費,多這300塊加個8g記憶體,加個1T硬碟,加幾個炫酷的風扇都能有更好的體驗,如果你覺得數字6比4要吉利,我覺得這是你唯一加錢公升級CPU的理由。 毛老表 你這個買貴了,看我分享的 毛老表 i5 10600kf比10400f只貴200...