简体   繁体   中英

Why is margin taken into account for absolute positioned elements?

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 ?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM