Home > Web Front-end > CSS Tutorial > How to Keep a DIV Fixed in Place While Scrolling?

How to Keep a DIV Fixed in Place While Scrolling?

Patricia Arquette
Release: 2024-11-21 03:53:13
Original
722 people have browsed it

How to Keep a DIV Fixed in Place While Scrolling?

How to Lock a DIV in Place on Scroll?

If you have a DIV that appears later on a page, you may want it to remain fixed in place once it becomes visible after scrolling. To achieve this, using only CSS was previously impossible. However, CSS advancements now make it feasible.

For a more detailed explanation, refer to this Stack Overflow answer: https://stackoverflow.com/a/53832799/1482443

If you prefer a jQuery solution, consider the following example:

var fixmeTop = $('.fixme').offset().top;
$(window).scroll(function() {
  var currentScroll = $(window).scrollTop();
  if (currentScroll >= fixmeTop) {
    $('.fixme').css({
      position: 'fixed',
      top: '0',
      left: '0'
    });
  } else {
    $('.fixme').css({
      position: 'static'
    });
  }
});
Copy after login

This jQuery code allows you to fix the position of a DIV with the class "fixme" once you scroll past its initial position.

The above is the detailed content of How to Keep a DIV Fixed in Place While Scrolling?. 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