Home >Web Front-end >CSS Tutorial >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; }
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'}); } });
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!