why does a Body Tag shift if you have a child with a top margin

走远了吗. 提交于 2019-12-25 16:54:50

问题


I have spent a good chunk of my time to figure this out. In case you have a div with some margin on the top. The body position as per the chrome dev tools start from the point where the div starts from. Basically it doesn't consider the margin for the offset. Though it does considers the same for height calculation.

Eg -

<body>
    <div> my content my content my content my content my content my content my content my
    </div>
</body>

I have created a jsFiddle for the same -- http://jsfiddle.net/tusharmathur/kW4v4/


回答1:


Because of collapsing margins: http://www.w3.org/TR/CSS2/box.html#collapsing-margins

This means that, when there is no padding or border getting in the way, two elements in the document flow will share their margins, like one big happy family.

body is absorbing the top margin of div.

This has been part of spec for aeons.

You can add 1px of padding or border to body to stop it from happening.

More details on collapsing margins can be found here - https://developer.mozilla.org/en-US/docs/Web/CSS/margin_collapsing



来源:https://stackoverflow.com/questions/21450855/why-does-a-body-tag-shift-if-you-have-a-child-with-a-top-margin

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