0

I can't understand why a div positioned as absolute inside a relative div overlaps other elements. As far as I can understand, its position should be fix in its relative div container and encompassed in it, shouldn't it?

My attempt:

#content {
  position: relative;
}

#overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  background-image: url(https://picsum.photos/800);
  background-size: cover;
}
<div id="before">
  some div
</div>
<div id="content">
  <div id="overlay">
    <div>Some text.</div>
    <div>Some text.</div>
    <div>Some text.</div>
    <div>Some text.</div>
    <div>Some text.</div>
    <div>Some text.</div>
    <div>Some text.</div>
    <div>Some text.</div>
  </div>
</div>
<div id="after">
  other div
</div>

I wonder why #content, positioned as relative, overlaps #after.

Temani Afif
  • 245,468
  • 26
  • 309
  • 415
Philippe
  • 1,134
  • 12
  • 22
  • 2
    When you position an element absolutely you are taking it out of the normal document flow. It is positioned relative to the body element in your example, of which `#content` is a child of. The real question is: what are you trying to achieve visually? – Terry May 30 '23 at 05:14
  • @Terry, thanks for your answer. In fact, this is a theoretical question for my own knowledge, relative to the first answer I made [here](https://stackoverflow.com/a/76323332/4698373). Could `sticky` make the job if I wanted to shift the image in it's parent without breaking the flow? – Philippe May 30 '23 at 05:26

1 Answers1

1

Absolute positioning from MDN docs,

The element is removed from the normal document flow, and no space is created for the element in the page layout. It is positioned relative to its closest positioned ancestor, if any; otherwise, it is placed relative to the initial containing block. Its final position is determined by the values of top, right, bottom, and left.

This value creates a new stacking context when the value of z-index is not auto. The margins of absolutely positioned boxes do not collapse with other margins.

If you want to maintain the flow then you need to remove position: relative from the parent.

Generally if you want child elements to be positioned relative to its current position without changing the layout around it, you apply position: relative on child.

Applying position: absolute places the child relative to the parent's position, changing the layout around it.

#content {
  background: red;
}

#overlay {
  position: relative;
  top: 200px;
  left: 0;
  width: 100%;
  background-image: url(https://picsum.photos/800);
  background-size: cover;
}
<div id="before">
  some div
</div>
<div id="content">
  <div id="overlay">
    <div>Some text.</div>
    <div>Some text.</div>
    <div>Some text.</div>
    <div>Some text.</div>
    <div>Some text.</div>
    <div>Some text.</div>
    <div>Some text.</div>
    <div>Some text.</div>
  </div>
</div>
<div id="after">
  other div
</div>
Tsubasa
  • 1,389
  • 11
  • 21