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

前端 未结 3 632
无人共我
无人共我 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:21

    From the notes on the top attribute in the CSS 2.1 specification:

    This property specifies how far an absolutely positioned box's top margin edge is offset below the top edge of the box's containing block. For relatively positioned boxes, the offset is with respect to the top edges of the box itself (i.e., the box is given a position in the normal flow, then offset from that position according to these properties).

    To me this implies that if no top is specified then the box is positioned to the top of its "natural" container (its parent). When top is specified it's then offset to the closest ancestor with relative or absolute positioning (which I assume html or body have by default).

    It then goes on to say:

    ...which cause the top of the outer box to be positioned with respect to its containing block. The containing block for a positioned box is established by the nearest positioned ancestor (or, if none exists, the initial containing block, as in our example).

提交回复
热议问题