1

Am a right to conclude that a CSS margin (e.g. margin-left) influences the final position of an absolute postioned element? It seems a negative margin-left pulls it to the left (of it's absolute postion), a positive value to the right (of it's absolute postion).

Can someone explain me more about the combination absolute positioned elements and margins?

Thanks.

  • 2
    Not much to explain, what you said is correct. – j08691 Jun 23 '14 at 19:22
  • 1
    Nothig to explain, its out of the flow and as you pull other elements with negative margin, same way you do with absolute, you can refer my answer on positioning [here](http://stackoverflow.com/questions/20718577/how-css-positions-work-why-absolute-elements-stack-up-on-each-other-instead-of/20718728#20718728) – Mr. Alien Jun 23 '14 at 19:23
  • It's a good question and, incidentally, I consider it in my book "Functional CSS." The book is available for free from amazon for today and tomorrow and you are welcome to check it out. – DRD Jun 23 '14 at 20:12

2 Answers2

2

Correct. Margins influence where the edges of an absolutely positioned element begin.

DRD
  • 5,557
  • 14
  • 14
1

Lets understand it this way:

When you have an statically-positioned element, the element is part of the normal flow of the document. Hence, any margins applied on it are considered 'with respect to its surrounding elements'.

When you have an relatively-positioned element, the element is still part of the normal flow of the document. Hence, any margins applied on it are still considered 'with respect to its surrounding elements'.

BUT,

When you have an absolutely-positioned element, the element is taken out of the normal flow of the document. This element's positioning is now dictated by the first parent container that is not statically positioned (or the top level body element as a fallback). Hence, when you apply margin, the parent container is taken as the 'surrounding element' and the margin in calculated with 'respect to it'.

Hope this helps.

JohnP
  • 49,507
  • 13
  • 108
  • 140
Satwik Nadkarny
  • 5,086
  • 2
  • 23
  • 41
  • `In essence, this element's positioning now has nothing to do with any other elements within the page`. This is not the case. The surrounding element is the first parent element that is either positioned relative, absolute or fixed. – JohnP Jun 23 '14 at 19:38
  • @JohnP I was only trying to provide a simplified answer with respect to a single element. Ofcourse, an absolutely positioned div within a relatively positioned div would take up its margins with respect to the parent div (relatively positioned div). But that would be over-complicating the answer here!! I just wanted the answer to convey the basic concept!! – Satwik Nadkarny Jun 23 '14 at 19:43
  • Would be clearer if you could apply the clarification for other people who come across the question and the answer. – JohnP Jun 23 '14 at 19:46