简体   繁体   中英

Absolutely positioned element is scrolled with content, why?

I have the following setup: (try scrolling the content)

HTML

<div class="wrapper">
  <div class="backdrop"></div>
  <div class="content">
    1<br>
    2<br>
    3<br>
    4<br>
    5<br>
    6<br>
    7<br>
  </div>
</div>

CSS:

.wrapper {
  height: 100px;
  overflow: auto;
  border: 1px solid black;
  position: relative;
}

.backdrop {
  position: absolute;
  top:0;
  left: 0;
  bottom:0;
  right: 0;
  background: red;
}

The problem is that backdrop for some reason is scrolled top with the content. Why is this happening? I was expecting the backdrop to remain still since it's positioned relative to the wrapper borders, not content's.

The scrollable area is defined by the wrapper via its overflow: auto declaration. Since wrapper serves as the containing block for both the content and the backdrop (due to position: relative ), this causes both elements to scroll together. In other words, this is due to both overflow: auto and position: relative on the same parent element, working in tandem.

Note that absolute positioning does not make an element immune to scrolling; when an absposed element does not appear to scroll, that is simply because its containing block does not scroll, and whatever is scrolling apart from the absposed element is some other element that is not its containing block. That is not the case in your setup. See the last example in section 11.1.1 of the spec for another example of this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM