Home >Web Front-end >CSS Tutorial >How to Make a Div Stick to the Screen Top on Scroll?

How to Make a Div Stick to the Screen Top on Scroll?

Barbara Streisand
Barbara StreisandOriginal
2025-01-06 01:03:41746browse

How to Make a Div Stick to the Screen Top on Scroll?

Making a Div Stick to the Screen Top on Scroll

Introduction:
Wanting to create a div that remains affixed to the top of the screen when scrolled to is a common web design requirement. This functionality is achievable through various methods, including CSS positioning and JavaScript manipulation.

CSS Positioning:
A straightforward approach is to use fixed positioning in CSS:

.fixedElement {
    position: fixed;
    top: 0;
    width: 100%;
    z-index: 100;
}

With this CSS, the element will remain in the same spot relative to the screen, regardless of scrolling. However, this method may not be suitable if the element needs to change its position dynamically based on the scrolled position.

JavaScript Manipulation:
To create a div that sticks to the top only when it has been scrolled to, you can use a combination of CSS and JavaScript. The idea is to change the element's position from absolute to fixed once it reaches a certain scroll offset:

$(window).scroll(function(e) {
  var $el = $('.fixedElement');
  var isPositionFixed = ($el.css('position') == 'fixed');
  if ($(this).scrollTop() > 200 && !isPositionFixed) {
    $el.css({'position': 'fixed', 'top': '0px'});
  }
  if ($(this).scrollTop() < 200 && isPositionFixed) {
    $el.css({'position': 'static', 'top': '0px'});
  } 
});

In this code:

  • $el represents the element with the class 'fixedElement'.
  • isPositionFixed checks if the element is already fixed in position.
  • When the scroll offset (determined by $(this).scrollTop()) reaches 200px and the element is not fixed, it is set to be fixed and positioned at the top.
  • When the scroll offset falls below 200px and the element is fixed, it is reset to its original position.

This approach provides flexibility in dynamically adjusting the element's position based on the scroll behavior.

The above is the detailed content of How to Make a Div Stick to the Screen Top 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