The position: sticky CSS property is used to create a sticky positioning effect for an element. When an element is set to position: sticky, it behaves like a relatively positioned element until it reaches a specified scroll position, at which point it becomes fixed in place.
Key Points:
- The element will scroll with the page until it reaches a defined offset (using
top,right,bottom, orleft). - Once the element reaches that offset, it will "stick" to that position and remain visible as the user continues to scroll.
- It is often used for headers or navigation menus that should remain visible at the top of the viewport while scrolling.
Example:
.sticky-header {
position: sticky;
top: 0; /* Sticks to the top of the viewport */
background-color: white;
z-index: 1000; /* Ensures it stays above other content */
}
HTML:
<div class="sticky-header">I am a sticky header</div>
<div class="content">... (more content here) ...</div>
In this example, the header will stick to the top of the viewport when you scroll down the page.
