2

I have a parent element (#container) with container-type: inline-size. Inside this element, I have a child element (#absolute) with position: absolute. This causes the absolute element to be positioned relative to #container. However, I would like to position it relative to the viewport.

As far as I know, this is caused by the container-type: inline-size rule which causes the parent element to serve as the containing block for the absolute element.

container-type: inline-size on #container is necessary to use container queries relative to the container's dimensions. And in my case, the absolute element is rendered inside #container and cannot be easily moved out.

The real-life use case for this is a main app #container and full-screen modals that are rendered inside the responsible components (which reside inside the main container).

#foo {
  width: 100px;
  height: 100px;
  background-color: lightgreen;
}

#container {
  container-type: inline-size;
  width: 200px;
  height: 100px;
  background-color: yellow;
}

#absolute {
  position: absolute;
  top: 0;
  left: 0;
  width: 80px;
  height: 50px;
  background-color: orange;
}
<html>

<body>
  <div id="foo">foo</div>
  <div id="container">
    <div id="absolute">Absolute</div>
  </div>

</body>

</html>

The child element (orange) is positioned relative to the parent (yellow). But I would like it to be relative to the viewport which would make it appear inside/on top of the green element.

References:

kspar
  • 63
  • 3
  • 1
    you cannot, the only way is to (1) get rid of container or (2) place the element outside – Temani Afif Apr 13 '23 at 12:42
  • Fun fact: a draft of this question was generated by ChatGPT after I explained the problem and it was unable offer a solution. Thanks, Temani - perhaps the AI was correct. However, I do hope that maybe somebody has encountered this problem and perhaps even found a hacky solution. – kspar Apr 13 '23 at 12:55

0 Answers0