Why doesn't an absolutely positioned element position itself relative to its parent if the parent is static?

StackOverflow https://stackoverflow.com/questions/23282083

  •  09-07-2023
  •  | 
  •  

Domanda

I've heard that an absolutely positioned element positions itself relative to its first non-statically-positioned ancestor. But is there some more holistic reason for this? Or is it just an arbitrary choice that was made, that it wouldn't be true for static elements.

I guess I'm wondering if there's some unified theory of CSS, so to speak, i.e. one that's perhaps complicated, but less complex. One which outlines the behavior of position and static and absolute in such a way that this interaction comes out of it as a natural consequence.

I also can't find an explicit reference to this rule in the CSS spec; that might help.

È stato utile?

Soluzione

Simply because forcing people to position their elements relative to the parent element is a needless limitation. What if I want to position an element relative to <body>? What if I want to position an element relative to a specific ancestor? Well, I could just set position: relative on the target parent. Without this, I'd need to use JS.

Of course, I don't think this is the best way it could be implemented. If I wrote the spec my self, I'd make it:

position: absolute(selector);

But of course, I don't write the spec.

Altri suggerimenti

static is the default position of any given element, unless you specify otherwise. And if absolute positioning would take that as a reference point, then you would not be able to position an element absolutely in reference to anything but its parent element.

Therefor, it was specified that absolute positioning takes the nearest ancestor element with a position other than static as reference point (or the viewport itself if there is none).

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top