I am trying to lock the green box to the very top of the when a user scrolls through the content. However, when you scroll there is a gap on top of the green box (as shown in the demonstration)
I've tried to set position to fixed for the green box, but it jumps out of the red box. So it needs to remain absolute.
Please look at the example I've set it up live here http://jsfiddle.net/jpXjH/839/
OR look at the code here
<div style="padding: 20px 0px; background-color:cyan;">
This is a header with some random content
</div>
<div style="width:480px; height:1400px; overflow:hidden; margin:auto;
border:1px solid gray; position:relative; background-color: #ff5d5d; ">
<div id="locked">
This element needs to be on the very top LOCKED when scrolled down.
However you can see there is a gap in the very top when you scroll.
</div>
</div>
<style>
#locked{
background-color: limegreen;
padding:10px;
width:150px;
position:absolute;
top:0;
right:0;
}
</style>
<script>
window.onscroll = changePos;
function changePos() {
var locked = document.getElementById("locked");
if (window.pageYOffset > 30) {
locked.style.position = "absolute";
locked.style.float = "right";
locked.style.top = pageYOffset + "px"
} else {
locked.style.position = "";
locked.style.top = "";
}
}
<script>
Thanks in advance
Simplest solution I can think of is to subtract the height of the locked bar at the top from the header.style.top you alter in your JS:
header.style.top = pageYOffset - 76 + "px"
obviously you can get the height directly from the element instead of hardcoding it.