Home >Web Front-end >CSS Tutorial >How to Make a Div \'Stick\' to the Top of the Screen When Scrolling Past It?
Problem:
You have a div that initially sits 100px from the top of the page and contains essential buttons or controls. When the user scrolls down past this div, you want it to "stick" to the top of the screen for easy access. When the user scrolls back up, you want it to return to its original position.
Solution:
The secret lies in utilizing the position:fixed property but only after the user has scrolled past the div. Here's how to achieve this:
JavaScript:
<code class="javascript">var $window = $(window), $stickyEl = $('#the-sticky-div'), elTop = $stickyEl.offset().top; $window.scroll(function() { $stickyEl.toggleClass('sticky', $window.scrollTop() > elTop); });</code>
This code captures the window's scroll event and dynamically applies a "sticky" CSS class when the user scrolls past the top of the div.
CSS:
<code class="css">#the-sticky-div.sticky { position: fixed; top: 0; }</code>
This CSS sets the "sticky" class to make the div adhere to the top of the screen. By default, position:fixed places the div relative to the window, ensuring it stays at the top throughout scrolling.
How it Works:
When the page loads, the div is positioned 100px from the top. As the user scrolls down, the JavaScript checks if the current scroll position exceeds the div's initial top position. If so, it applies the "sticky" class to the div, causing it to become fixed to the top of the screen. When the user scrolls back up, the process is reversed, and the "sticky" class is removed, allowing the div to resume its initial position.
In summary, this solution effectively makes a div "cling" to the top of the screen when a user scrolls past it while allowing it to return to its original position when the user scrolls back up.
The above is the detailed content of How to Make a Div \'Stick\' to the Top of the Screen When Scrolling Past It?. For more information, please follow other related articles on the PHP Chinese website!