问题
Having the HTML below
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<body>
<div style="width:400px;height:200px;background-color:Gray;margin-bottom:10px;"></div>
<div style="width:400px;height:200px;background-color:Green;margin-top:10px;"></div>
</body>
</html>
the space between those two DIVs is only 10 pixels.
Why? Explain please.
回答1:
That behavior is called collapsing margins. The margin values are not added but the higher value is used:
Vertical margins may collapse between certain boxes:
- Two or more adjoining vertical margins of block boxes in the normal flow collapse. The resulting margin width is the maximum of the adjoining margin widths. […]
- […]
回答2:
Here is a good explanation of margin collapsing. Basically, it seems that all adjacent margins will collapse into each other, per the CSS specification and against all common sense.
回答3:
if you want to have the desired effect you can use "padding" instead, margins always collapse
来源:https://stackoverflow.com/questions/936186/css-margin-strange-behavior-why