Home >Web Front-end >CSS Tutorial >How to Keep a Div Fixed at the Top of the Screen on Scroll?

How to Keep a Div Fixed at the Top of the Screen on Scroll?

Linda Hamilton
Linda HamiltonOriginal
2024-12-16 22:54:11751browse

How to Keep a Div Fixed at the Top of the Screen on Scroll?

Fixing Position of a Div at the Top of the Screen on Scroll

To create a div that sticks to the top of the screen once it's scrolled to, you can utilize CSS's position property. Consider the following CSS snippet:

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

Edit:

To ensure the element sticks properly, it should initially have its position set to absolute. Once the document's scroll offset reaches the element's top boundary, you can dynamically change its position to fixed and reset its top property to 0.

The following JavaScript code snippet demonstrates how to achieve this using the scrollTop function:

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

When the scroll offset surpasses 200 pixels, the element will become fixed at the top of the browser window.

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