Home >Web Front-end >CSS Tutorial >How Can I Make a Div Stick to the Top of the Screen on Scroll?

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

DDD
DDDOriginal
2024-12-19 18:54:21762browse

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

Making a Div Stick to the Top of the Screen While Scrolling

Creating a div that remains fixed at the top of the screen after a certain scroll threshold can be achieved using CSS or JavaScript.

CSS Solution

Using CSS, you can position the div as fixed once its top edge reaches the top of the screen:

.fixed-div {
    position: fixed;
    top: 0;
    width: 100%;
    z-index: 100;
}

JavaScript Solution

With JavaScript, you can dynamically change the position of the div when the scroll position reaches a specific value:

$(window).scroll(function(e) {
    var $div = $('.fixed-div');
    var scrollTop = $(this).scrollTop();
    if (scrollTop > 200) {
        $div.css('position', 'fixed');
        $div.css('top', '0');
    } else {
        $div.css('position', 'static');
        $div.css('top', '0');
    }
});

In this script, the jQuery scroll() function is used to listen for scroll events. When the scrollTop position exceeds 200, the div is given a fixed position and set to the top of the page. When the scrollTop drops below 200, the div reverts back to a static position.

The above is the detailed content of How Can I 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