Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
614 views
in Technique[技术] by (71.8m points)

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

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/

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...