Search code examples
htmlcsscss-position

How to use CSS absolute position inside a scrollable div element


I have the following HTML content. I have multiple elements (e.g., div with id = one, two, three) inside a div container which is scrollable.

In each element, I need to use CSS position 'absolute' which position related to its parent div (i.e., class='Anchor').

The problem I am having is, when I scroll the outer container, none of the divs with an absolute position moved. My understanding of position 'absolute' is it is positioned relative to its parent DIV element. How can I make those 'absolute' position move as I scroll the outer container?

<div style="overflow-y: scroll">
   <div>
      <div class="Anchor" id="one">
           <div style="position: absolute"> something </div>
           <div style="position: absolute"> something else </div>
      </div>
   </div>
   <div>
      <div class="Anchor" id="two">
           <div style="position: absolute"> something </div>
           <div style="position: absolute"> something else </div>
      </div>
   </div>
   <div>
      <div class="Anchor" id="three">
           <div style="position: absolute"> something </div>
           <div style="position: absolute"> something else </div>
      </div>
   </div>
</div>

Solution

  • You must set position: relative; on the parent div to get the child elements to move in relation to it.

    The reality is, you can have the parent div set to any user-defined position, as long as the default static position isn't being used.