2

Assume the following HTML:

body {
  margin: 0;
  padding: 0;
  background-color: fuchsia;
}

#item {
  position: absolute;
  top: 0;
  left: 0;
  margin-top: 20px;
  margin-left: 10px;
  background-color: aqua;
}
<div id="item">
  Hello
</div>

Since the element is absolutely positioned, I'm expecting the margin-top and margin-left properties to be ignored here. However, I find the element aligned 20px to the top and 10px to the left. (Using Chrome 77 here)

Can someone provide an explanation as to why/how the margin are taken into account here ?

Tyler Roper
  • 21,445
  • 6
  • 33
  • 56
GoldenCrystal
  • 83
  • 1
  • 5
  • The `top` and `left` properties are in reference to the nearest positioned parent (or the `` tag in your case since there's no positioned parent). The margin is applied to the `#item` in your code, so it has nothing to do with that. `#item` is positioned at the `left: 0` and `top: 0` of the `` tag and it has `20px` margins on both its top and left side. – volt Feb 05 '20 at 17:56
  • Does this answer your question? [CSS absolute positioned elements and margins](https://stackoverflow.com/questions/24373683/css-absolute-positioned-elements-and-margins) – disinfor Feb 05 '20 at 17:57
  • Why you expect the margin to be ignored? we center absolute with margin (https://stackoverflow.com/q/59723642/8620333) – Temani Afif Feb 05 '20 at 18:02

1 Answers1

6

Because that's what the spec says:

An absolutely positioned element is an element whose computed position value is absolute or fixed. The top, right, bottom, and left properties specify offsets from the edges of the element's containing block. (The containing block is the ancestor relative to which the element is positioned.) If the element has margins, they are added to the offset. The element establishes a new block formatting context (BFC) for its contents.

Also: https://www.w3.org/TR/CSS2/visuren.html#propdef-position

...though absolutely positioned boxes have margins, they do not collapse with any other margins.

j08691
  • 204,283
  • 31
  • 260
  • 272