Fixing a Div on Scroll with CSS
Your question pertains to making a div remain fixed after scrolling to it. As you mentioned, simply applying position: fixed to the div causes it to appear before it should on the page.
Fortunately, advancements in CSS now allow for this functionality:
div { position: sticky; top: 0; }
The sticky position property ensures that the div remains fixed once it reaches the top of the viewport, similar to how the second ad on 9gag behaves.
jQuery Alternative
For compatibility with older browsers, here's the original jQuery approach:
$(window).scroll(function () { var scrollTop = $(window).scrollTop(); var divOffset = $('.fixme').offset().top; if (scrollTop >= divOffset) { $('.fixme').css({ position: 'fixed', top: '0', left: '0' }); } else { $('.fixme').css({ position: 'static' }); } });
The above is the detailed content of How Do I Fix a Div to the Top of the Viewport on Scroll with CSS?. For more information, please follow other related articles on the PHP Chinese website!