Search

5/26/2010

margin collapse

CSS tutorial - Margin Collapsing

case 1:
16 pixels
A
16 pixels
100 pixels
50 pixels
16 pixels
B
16 pixels

The middle paragraph is 0px high, so its margins are touching. So there are 4 margins touching each other. The gap between A and B is max(16,100,50,16), which is 100 pixels.

case 2:

Negative margins are special and are dealt with as follows:

1. Work out what margins are touching.
2. Ignore all negative margins.
3. Perform the collapse as if there were no negative margins.
4. Select the largest of the negative margins, and subtract it from the computed margin from step 3.

<p style="margin-bottom:-5px;">A</p>
<p style="margin-top:100px;margin-bottom:-50px;"></p>
<p>B</p>

16
A
-5
100
-50
16
B
16

Step 2, ignoring the negative margins:
16
A
100
16
B
16

Step 3: The gap between A and B is max(100,16), which is 100 pixels.
Step 4, subtracting the largest negative margin:
Max(5,50) is 50.
100 - 50 = 50
So the resulting gap between A and B is 50 pixels.

case 3:
<div style="margin-top:10px">
<div style="margin-top:20px">
A
</div>
</div>

There are two margins touching each other: 10 and 20 pixels. The resulting margin will be max(10,20), which is 20 pixels.

The question is; where does the 20 pixels appear:
1. Before the outer DIV?
2. Before the inner DIV but inside the outer DIV?

(In other words, if the background of the outer DIV is red, and the background of the inner DIV is white, should any red be visible?)

The answer is quite simple; the resulting margin always appears as far out as possible - outside the outermost element whose margin is taking part in the collapse. Even though the margin that gets "used" is the one from the inner DIV, it appears outside the outer DIV. So it seems to appear in the wrong place.
The solution to the unwanted gap, is to make sure the margin collapse cannot happen. The way to do that is to make sure the 0 pixel top margin of the DIV and the 16 pixel top margin of the paragraph cannot touch each other. This is where the box model becomes useful. It is possible to remove the margin of the paragraph, but it is also possible to manipulate the DIV to insert something between the paragraph's top margin, and the DIV's 0 pixel top margin. The way to do that is to add a top padding or top border of at least 1 pixel of height onto the DIV, since they sit between the two margins.

Minz Meyer's Researchkitchen - CSS - Auto-height and margin-collapsing
关于float元素的margin collapse问题 - web k(客)~ - JavaEye技术网站

沒有留言: