Home >Web Front-end >CSS Tutorial >How Do I Fix a Div to the Top of the Viewport on Scroll with CSS?

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

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-15 07:37:02971browse

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;
}

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!

Statement:
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