Why is a div with “position: absolute” not by default relative to the document?

前端 未结 3 637
无人共我
无人共我 2020-12-20 07:38

I thought a general rule is that, whenever a div foo has position: relative, then if none of the parent and ancestor has any non-static posit

3条回答
  •  情书的邮戳
    2020-12-20 08:03

    It is positioned relatively to the document (that's the reason why top: 0 moves it all the way to the top), but if you don't set top to any value (i.e. you leave it as auto), the box has no reason to shift anywhere from its static position (where it would normally sit if you hadn't set position: absolute).

    See also this answer and sections 9.3 and 10 of the spec. Section 10, in particular, contains all the rules that govern static positioning, and is quite a comprehensive if not overly technical read.

    The exact rule that says an element should remain in the static position in such a scenario is in section 10.6.4. In your scenario, you don't set top or bottom, but you do set height, so the second rule among the six that are listed applies:

    2. 'top' and 'bottom' are 'auto' and 'height' is not 'auto', then set 'top' to the static position, set 'auto' values for 'margin-top' and 'margin-bottom' to 0, and solve for 'bottom'

    So an absolutely-positioned element needs to remain in its normal static vertical position if top is not given something other than auto — it's not supposed to move itself arbitrarily.

    Also, the containing block of an absolutely-positioned element is always either its nearest positioned ancestor if there is one, or the initial containing block.

提交回复
热议问题