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

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

Patricia Arquette
Patricia ArquetteOriginal
2024-11-12 00:24:03575browse

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

How to Fix a Div to the Top of the Screen on Scroll

When scrolling through a website, you may want to keep certain elements stationary at the top of the screen. To achieve this, CSS properties such as position and top can be manipulated.

CSS Solution:

You can use CSS to fix an element to the top of the screen using the fixed positioning:

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

JavaScript Solution:

For more control over the element's behavior, you can use JavaScript and the scrollTop function to detect the page's scroll offset. Here's an example:

$(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 &amp;&amp; isPositionFixed){
    $el.css({'position': 'static', 'top': '0px'}); 
  } 
});

In this code, when the scroll offset exceeds 200 pixels, the element's position is changed to fixed, and when the offset drops below 200 pixels, the element returns to its original position and is no longer fixed to the top.

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