Re: [問題] CSS margin-top的問題

作者: eight0 (欸XD)   2016-12-15 12:52:54
先記好,margin 的意義是留白
假如兩個 block 長這樣︰
<div class="a">Hello</div>
<div class="a">Hello</div>
對 .a 指定「上下留白 30px」,兩個 block 之間的留白有多高?
30px,符合預期。對任意一個 block 來說,上下的確都有了 30px 的留白
若是長這樣︰
<div class="a">Hello</div>
<div class="b">
<div class="c">Hello</div>
<div class="c">Hello</div>
</div>
並且對 .b, .c 指定「上下留白 30px」,
.a 和 .b 之間的留白有多高?.a 和 .c 之間的留白有多高?
30px,符合預期。對 .b 和 .c 來說,上下的確都有了 30px 的留白
總之,這不是一個「不如預期」的規範。下面直接引用 spec 的說明
> In CSS, the adjoining margins of two or more boxes (which might or might
> not be siblings) can combine to form a single margin. Margins that combine
> this way are said to collapse, and the resulting combined margin is called
> a collapsed margin.
http://codepen.io/eight04/pen/eBQvWR
上面的連結包括 margin collapsing 的範例和一些解法。用 inline-block 的確可以
避免這個現象(因為這個特性是 block 獨有),但我認為只因這個理由就把本來是
block 的東西設為 inline-block 不太適合。
作者: i94eric (桃園世凱)   2016-12-16 19:12:00

Links booklink

Contact Us: admin [ a t ] ucptt.com