Sticky top div with absolute positioning

Henrik Janbell picture Henrik Janbell · Nov 30, 2011 · Viewed 35.3k times · Source

I'm using absolute positioning to have a div fill up the entire browser window. However, I wan't to combine this with a sticky div that sometimes is there and sometimes not.

To make things a little clearer, check out this jsFiddle: http://jsfiddle.net/henrikandersson/aDdRS/

I want the "top", "left" and "subheader" to stay where they are at all times. I also want the "content" div to fill up what is left of the window. However, sometimes I want to display the "alert" div before "content". So far so good, as you can see in the jsFiddle. But, I want "alert" to stick to the "subheader" and stay there when scrolling. As you can see if you resize the window, "alert" will now be scrolled along with "content" - I don't want it to be.

Anyone got an idea of how to solve this?

EDIT: I made a change in my jsFiddle, I placed the "alert" where it should be (between subheader and content-area). As you can see ( http://jsfiddle.net/henrikandersson/aDdRS/12 ) it does not push the "content-area" down since content-area has top:20px. And I can't set top:40px for example since "alert" should be able to vary in height and I want content-area to have the same css with or without the alert above.

EDIT #2: This question deals with the same problem, but there is no solution for that question either. Seems like it's not possible without using JavaScript: variable height scrolling div, positioned relative to variable height sibling

Answer

NamNamNam picture NamNamNam · Jun 18, 2018

2018-6-18

I choose the CSS way with position: sticky.

that https://github.com/abouolia/sticky-sidebar .
doesn't work for me (I am using Vue.js 2.0 SPA with vue-router & vuex)

I also want the element position: absolute first,
and then position: sticky

Solution

  1. parent HTML element use position: absolute to have the right position.

(don't forget to set height for parent. for example height:100%)

  1. child HTML element position: sticky

work for me. enter image description here

enter image description here