CSS margin strange behavior, why?

筅森魡賤 提交于 2020-01-11 10:10:14

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!