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
Release: 2024-12-16 22:54:11
Original
817 people have browsed it

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;
}
Copy after login

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

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!

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