R2D2
R2D2

Reputation: 2640

fixed header, then scroll with content

I have a layout that is to start with a fixed header, containing a logo, etc.

Further down the page is content.

The fixed header should stay fixed as the user starts to scroll, but then as the content scrolls up the screen and comes close to touching the fixed header area, then the fixed header scrolls off the screen along with the content.

I have managed to sort of get this working using the following:

<script>

$(document).ready(function(){

$(window).scroll(function(){
if($(this).scrollTop() >= ($("#headerarea").height() + 85)) { $("#headerarea").removeClass("header-fixed"); $("#headerarea").addClass("header-scroll"); } else { $("#headerarea").removeClass("header-scroll"); $("#headerarea").addClass("header-fixed"); }
});

});

</script>

My CSS includes:

.header-fixed {
position: fixed;
top: 0px;
left: 0px;
width: 100%;
height: 140px;
z-index: 150;
}

.header-scroll {
position: absolute;
top: 225px;
left: 0px;
width: 100%;
height: 140px;
z-index: 150;
}

This allows the header area to stay fixed until the page scrolls to within 85 pixels of the header area, and then the header becomes normally scrolling with the rest of the page content.

This seems to work ok if I scroll the page using the scrollbar slowly.

But if I scroll quickly, or use a mouse wheel, then the header 'jumps' a lot.

Like when using the mouse scroll wheel, the header will jump down the page with the scrolling content, past the position it should stay fixed, then it will see that it has passed that position and jump back up to the fixed position again. This doesnt look good at all.

But I cant think of any other way to get this same effect.

Any suggestions on how to get this working better?

EDIT: Position:sticky seems to work, but I would ideally like to have a solution that will also work on IE, which position:sticky wont do.

Upvotes: 0

Views: 958

Answers (1)

puddi
puddi

Reputation: 811

Have you looked into position: sticky;? I think it's describing a lot of what you want here. Notably, the sticky stuff will go back to scrolling with the rest of the content once its parent div is outside of the viewport. https://css-tricks.com/position-sticky-2/

Upvotes: 1

Related Questions