Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
595 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 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...