Home >Web Front-end >CSS Tutorial >How to Make a DIV Element Fixed on Scroll?

How to Make a DIV Element Fixed on Scroll?

DDD
DDDOriginal
2024-11-29 13:05:11800browse

How to Make a DIV Element Fixed on Scroll?

How to Position a DIV Fixed on Scroll

This query explores how to make a div remain fixed after scrolling to a specific point on the page. The idea is to create an effect similar to the second advertisement on websites like 9gag, which appears fixed as you scroll down past a certain point.

While CSS alone does not currently provide a solution, a combination of CSS and JavaScript can achieve this effect.

Using the jQuery approach:

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

In this code, fixme represents the DIV to be positioned fixed. This approach adds an event listener that tracks the scroll position and compares it to the DIV's initial position. When the scroll position exceeds the DIV's initial position, the CSS properties position, top, and left are set to fix the DIV in place. Otherwise, the CSS property position is set to static to allow the DIV to scroll normally.

The above is the detailed content of How to Make a DIV Element Fixed on Scroll?. 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