Shawn Taylor
Shawn Taylor

Reputation: 3969

Why margins behave same for position absolute/relative

I see top/left properties display difference with position absolute and position relative as it should.

When I set margin-top on position:relative it positions correctly according to containing container. BUT when I set margin-top on position:absolute, I think it should be positioned according to BODY element but it is positioned same as position:relative which is relative to containing element (#container). And I have not set any element non-static as well.

Here is code with position:relative http://jsfiddle.net/uFta4/

And here is with position:absolute http://jsfiddle.net/uFta4/2/

Please note that #firstDiv is positioned at same location which is relative to #container.

Should it be relative to BODY element?

Upvotes: 1

Views: 1529

Answers (2)

Gary Lindahl
Gary Lindahl

Reputation: 5363

Its because there is difference between RP and AP elements in a sense that RP elements 'collapse' their margins while AP element doesn't collapse their margin. That's why you are seeing AP element at same position because its also counting BODY margin you gave in its tag.

To make you understand better I have put couple of codes. Look at following variations and observe different behavior margin collapsing of RP and AP elements. RP

  1. RP element margin collapse http://jsfiddle.net/uFta4/6/
  2. AP element margins is added http://jsfiddle.net/uFta4/7/
  3. AP elements with -ve margin added (becomes -20px) http://jsfiddle.net/uFta4/9/
  4. RP elements with -ve margin collapse(doesn't become -30px) http://jsfiddle.net/uFta4/10/

I hope now it will be clear to you.

Upvotes: 1

user166560
user166560

Reputation:

Margins are supposed to behave the same for position:absolute and position:relative.

In your first example, the relatively positioned element doesn't have position values set, so there's no effect.

In your second example, the absolutely positioned element doesn't have position values set, either, so it's at the top left corner of the body. That's 60px from the top to account for a 20px margin on the body and a 40px margin on the element itself.

And, to quote from the specification ...

Margins of absolutely positioned boxes do not collapse (not even with their in-flow children).

Upvotes: 1

Related Questions