css - 關(guān)于margin折疊的一個(gè)問題。
問題描述
我在閱讀CSS2.2,但是我真的無法理解這句話的意思,以及它所適合的場(chǎng)景:
If the top and bottom margins of an element with clearance p. 157 are adjoining, its margins collapse with the adjoining margins of following siblings but that resulting margin does not collapse with the bottom margin of the parent block.
StackOverflow上有個(gè)家伙也提了一樣的問題,回答者的答案我也不理解。。。
借用采納者的知乎鏈接,這句的意思是:
If the top and bottom margins of an element with clearance are adjoining, its margins collapse with the adjoining margins of following siblings but that resulting margin does not collapse with the bottom margin of the parent block.(有間隙不折疊)
哪,什么才是有間隙呢?這里的間隙clearance在css2.2中有定義。來個(gè)例子,先有個(gè)直觀的理解吧:
<html><head> <style>* {padding: 0; margin: 0;}#b1 { width: 300px; height: 100px; margin-bottom: 4em; background-color: #0d8ba1;}#F { float: left; width: 100px; height: 70px; background-color: yellow;}#b2 { /*clear: both;*/ width: 300px; height: 100px; background-color: red; margin-top: 2em;} </style></head><body><p id='b1'></p><p id='F'></p><p id='b2'></p></body></html>
運(yùn)行時(shí),對(duì)比#b2有clear:both與沒clear:both時(shí),b1與b2margin的折疊情況。
設(shè)置clear:both之后,#b2為了避開浮動(dòng)的F,往下移動(dòng),出現(xiàn)了clearance也就是空隙,b1與b2不再折疊!
另外,stack overflow那個(gè)家伙的答案我沒再細(xì)究。pass。
問題解答
回答1:可以看這里:https://www.zhihu.com/question/24563593
回答2:這個(gè)說明也挺清晰的:http://www.raccoon-tech.com/css-margin-collapse
回答3:只要理解 clearance 產(chǎn)生的條件是當(dāng) clear 的元素在沒有被 clear 的時(shí)候(正常時(shí)),它的 boarder top 要比 float 元素的 boarder bottom 要高。如果 clear 的元素本來就在 float 元素下面,就不會(huì)產(chǎn)生 clearance。
If this hypothetical position of the element’s top border edge is not past the relevant floats, then clearance is introduced, and margins collapse according to the rules in 8.3.1.
所以這個(gè)規(guī)則大白話就是:對(duì)于一個(gè)帶 clearance 的元素,當(dāng)它 margin top 和 margin bottom 相鄰時(shí)(比如 height 為 0 、沒有 padding 和 border),這個(gè)兩個(gè) margin 會(huì)跟接下來相鄰元素的 margin 一起計(jì)算 collapsing,但不會(huì)跟父元素的 margin bottom 計(jì)算(這情況下就是只算這兩個(gè) margin)。
這里還要注意 clearance 計(jì)算是以 boarder edge 做參考,所以對(duì)于 margin top 和 margin bottom collapse 的元素,最后要注意還會(huì)吞掉與 margin top 相當(dāng)?shù)母叨取?/p>
Then the amount of clearance is set to the greater of:
The amount necessary to place the border edge of the block even with the bottom outer edge of the lowest float that is to be cleared.
The amount necessary to place the top border edge of the block at its hypothetical position.
相關(guān)文章:
1. 一個(gè)mysql聯(lián)表查詢的問題2. 運(yùn)行python程序時(shí)出現(xiàn)“應(yīng)用程序發(fā)生異常”的內(nèi)存錯(cuò)誤?3. html5 - iOS的webview加載出來的H5網(wǎng)頁,怎么修改html標(biāo)簽select的樣式字體?4. mysql - 一個(gè)表和多個(gè)表是多對(duì)多的關(guān)系,該怎么設(shè)計(jì)5. java - 我現(xiàn)在一個(gè)servlet中有調(diào)用socket訪問,作為socket的客戶端,6. python 如何實(shí)現(xiàn)PHP替換圖片 鏈接7. python如何不改動(dòng)文件的情況下修改文件的 修改日期8. 主從備份 - 跪求mysql 高可用主從方案9. javascript - git clone 下來的項(xiàng)目 想在本地運(yùn)行 npm run install 報(bào)錯(cuò)10. mysql主從 - 請(qǐng)教下mysql 主動(dòng)-被動(dòng)模式的雙主配置 和 主從配置在應(yīng)用上有什么區(qū)別?
