Home > Web Front-end > CSS Tutorial > How to Create a Sticky Div That Affixes to the Top of the Screen on Scroll?

How to Create a Sticky Div That Affixes to the Top of the Screen on Scroll?

Susan Sarandon
Release: 2024-12-29 04:18:17
Original
442 people have browsed it

How to Create a Sticky Div That Affixes to the Top of the Screen on Scroll?

Creating a Sticky Div That Affixes to the Top of the Screen

Issue:

You seek to create a div that remains beneath a content block initially. However, upon scrolling down the page and reaching the div's top boundary, it becomes fixed and scrolls alongside the page.

Resolution:

Employing CSS with a fixed positioning attribute achieves the desired functionality:

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

Edit:

To ensure the div remains sticky, it should initially have absolute positioning. Upon reaching the element's scroll offset, the positioning changes to fixed, with the top position set to zero.

Detect the document's top scroll offset 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 reaches 200, the element becomes fixed and sticks to the top of the browser window.

The above is the detailed content of How to Create a Sticky Div That Affixes to 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