如下三個div將會會如何放置(margin collapsing)?css
<style> body { margin: 0; } .first { margin: 20px; height: 500px; background-color: #666; } .second { margin: -10px; height: 300px; background-color: #999; } .third { margin: -30px; height: 100px; background-color: #ccc; } </style> <div class="first"> <div class="second"> <div class="third"> 三個元素的外邊距摺疊 </div> </div> </div>
同一個BFC中,相鄰的塊狀元素都是垂直放置嗎?html
如何清除浮動?根據什麼原理?app
如何對左側欄200px,主內容自適應進行佈局?佈局
如何使用margin完成聖盃佈局(左側x px,右側y px,中間自適應),用flex呢?測試
如下三個div將會會如何放置?flex
在同一個BFC中,相鄰的塊狀
元素會發生摺疊。兩個margin值都是正值,取最大值,都是負值,取最小值,一正一負則相加。那麼如題有三個呢,是從父元素往子元素算起,仍是子元素往外算起?若是從外往裏算,是0,從內往外算是-10px。經測試,是從內往外計算。code
live demohtm
同一個BFC中,相鄰的塊狀元素都是垂直放置嗎?get
不必定,設置writing-mode
值。查看如下Demo。it
如何清除浮動?根據什麼原理?
緊挨的塊級元素設置clear both
來清除浮動,通常 會經過:after
清除浮動。如Bootstrap的clearfix
。
.clearfix { display: table; content: " "; clear: both }
使父級元素觸發一個新的BFC,如overfow:hidden
或者display:table
。
如何對左側欄200px,主內容自適應進行佈局?
左欄設置200px的寬,設置浮動,主內容設置overflow:hidden
觸發一個BFC。由於BFC不會與浮動摺疊,因此右側會自適應。
如何使用margin完成聖盃佈局(左側x px,右側y px,中間自適應),用flex呢?
聖盃佈局大體結構以下
<div class="header"></div> <div class="container"> <div class="main"></div> <div class="left"></div> <div class="right"></div> </div> <div class="footer"></div>
步驟以下:
.container設置內邊距,留出放置左右固定寬度側欄的寬度。設置min-width:x px
(content-box)下,若是.left寬度大於父元素content-box的寬度,本身會被擠下去。
.main,.left,.right設置浮動,.main設置100%的寬度。.main位置固定。
.left設置x px寬度,設置margin-left爲-100%,此時與.main左上角重合,設置position:relative
,left設爲-x px或者right設置x px,.left位置固定。
.right設置y px寬度,把margin-left設爲-y px,此時與.main右上角重合,相對定位回到本身的位置。(或者margin-right小於等於-y px,最後不用定位,查看margin demo2)。
footer設置clear:both
清除浮動,或者container設置爲display:table
或者overflow:hidden
閉合浮動。使.footer回到正常位置。
另外有flex佈局就簡單多了。須要注意的是使用margin會把.main放在最前邊。而flex能夠按照.left,.main,.right的順序放置。另外flex佈局也不會出現中間擠掉兩邊的狀況。