Maximus Maximus - 1 year ago 54
HTML Question

Absolutely positioned element is scrolled with content, why?

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


<div class="wrapper">
<div class="backdrop"></div>
<div class="content">


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

.backdrop {
position: absolute;
left: 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.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download