Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does margin-top affect the placement of an absolute div?

Tags:

html

css

I have two divs in this jsFiddle - http://jsfiddle.net/z4062jfn/ - with absolute positioning. I didn't expect any margin values given to the divs to affect their absolute position. And this is true for a margin-bottom value given to the top div (uncomment line 8 of CSS). But a margin-top value given to the bottom box (uncomment line 19 of CSS) does move the bottom div position down by that amount.

What is there in this situation that lets a margin rule override an absolute position rule - sometimes?

<div id="box1"><p>box 1</p></div>
<div id="box2"><p>box 2</p></div>
like image 760
Steve Avatar asked Jan 09 '23 18:01

Steve


1 Answers

The simple factual explanation for why this happens is that the offset properties top, right, bottom and left actually respect the corresponding margin properties on each side. The spec says that these properties specify how far the margin edge of a box is offset from that particular side. The margin edge is defined in section 8.1.

So, when you set a top offset, the top margin is taken into account, and when you set a left offset, the left margin is taken into account.

If you had set the bottom offset instead of the top, you'll see that the bottom margin takes effect. If you then try to set a top margin, the top margin will no longer have any effect.

If you set both the top and bottom offsets, and both top and bottom margins, and a height, then the values become over-constrained and the bottom offset has no effect (and in turn neither does the bottom margin).

If you're looking to understand why the spec defines offsets this way, rather than why browsers behave this way, then it's primarily opinion-based, because all you'll get is conjecture. That said, Fabio's explanation is quite reasonable.

like image 165
BoltClock Avatar answered Mar 03 '23 23:03

BoltClock