Home >Web Front-end >CSS Tutorial >How Can I Create a Floating Div That Stays Fixed on Scroll?
Floating Div on Scroll: A Comprehensive Guide
Ever encountered the need for a div that remains fixed at the top of the screen after scrolling past its initial position? This common web development scenario can be achieved with ease, and this article will provide you with a detailed roadmap.
To begin, consider the CSS solution. By setting the div's position as fixed, you can ensure it remains in place:
.fixedElement { background-color: #c0c0c0; position: fixed; top: 0; width: 100%; z-index: 100; }
However, for a more dynamic approach, consider using jQuery. Position the div absolutely initially, and upon reaching the desired scroll position, switch to a fixed position with a zero top offset:
$(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'}); } });
With the scrollTop function, detect when the scroll offset reaches the specified point (e.g., 200 pixels). At this threshold, toggle the element's position accordingly, ensuring it "sticks" to the top of the screen on scroll.
The above is the detailed content of How Can I Create a Floating Div That Stays Fixed on Scroll?. For more information, please follow other related articles on the PHP Chinese website!