Log in

View Full Version : absolute and sticky positioning at the same time



gib65
10-25-2017, 04:51 PM
Hello,

I've got a scrollable div with a list of items in it:

6212

I want to add a panel overtop it with 50% opacity. It should remain fixed at the top with the list of item visible behind it:

6213

For the above image, I specified the CSS of the panel like so:


<div style="width: 100%; height: 200px; background-color: black; opacity: 0.5; z-index: 10; position: absolute; top: 0; left: 0;"></div>

This accomplishes the requirement of having the list of item behind it visible, but it doesn't remain fixed when I scroll.

So then I tried this:


<div style="width: 100%; height: 200px; background-color: black; opacity: 0.5; z-index: 10; position: sticky; top: 0; left: 0;"></div>

6214

That fixed the panel but as you can from the image above, it pushes the list of items down so that they don't appear behind the panel.

What would be the solution to this?

molendijk
10-27-2017, 04:17 PM
Try this:
<div style="position: relative; max-height: 400px; width: 40%; margin: auto; border: 1px solid black; overflow: auto; ">
<div style="position: fixed; width: calc(40% - 5px); height: 200px; background: black; opacity: 0.5; z-index: -1"></div>
<div style="padding: 10px">
item<br>item<br>item<br>item<br>item<br>item<br>item<br>item<br>item<br>item<br>item<br>item<br>item<br>item<br>item<br>item<br>item<br>item<br>item<br>item<br>item<br>item<br>item<br>item<br>item<br>item
</div>
</div>

If you want clickable elements in the panel, remove z-index: -1 and replace width: calc(40% - 5px) with something like width: calc(40% - 17px) or use javascript to make the width of the fixed panel as wide as 40% (in this case) minus the width of the browser's scrollbar.