How Do I Fix a Div to the Top of the Viewport on Scroll with CSS?

Mary-Kate Olsen
Release: 2024-11-15 07:37:02
Original
922 people have browsed it

How Do I Fix a Div to the Top of the Viewport on Scroll with CSS?

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;
}
Copy after login

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'
    });
  }
});
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template