CSS position: sticky
A sticky element switches between relative and fixed depending on the scroll position. It stays relative until a certain scroll point is reached, then it sticks in place like a fixed element.
Note: You must set at least one of top, right, bottom, or left for sticky positioning to work.
Example
When the sticky element reaches the top of the page (top: 0), it sticks there.
<style> block, give a div.sticky class position sticky, top 0, a green background, and a green border. Add a sticky div followed by enough content to scroll, so the div sticks to the top once it reaches it.
Output: complete HTML page
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
div.sticky {
position: sticky;
top: 0;
background-color: green;
color: white;
padding: 10px;
border: 2px solid #4CAF50;
}
</style>
</head>
<body>
<p>Scroll down this page. The green box sticks to the top once it reaches it.</p>
<div class="sticky">I am sticky!</div>
<div>
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</p>
<p>Sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.</p>
<p>Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper.</p>
<p>Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat.</p>
<p>Vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan.</p>
<p>Et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis.</p>
</div>
</body>
</html>
Common Uses for Sticky Positioning
Sticky positioning is often used for sticky headers (navigation bars that stay at the top while scrolling), sticky sidebars, and sticky table headers.
Compared with fixed: a sticky element acts like a relative element at first and takes up space in the document, sticking only after a scroll threshold, and it respects its parent's boundaries. A fixed element is always pinned to the viewport, takes up no space, and ignores its parent.
All CSS Positioning Properties
A summary of the positioning properties:
bottom— sets the bottom edge of a positioned box.clip— clips an absolutely positioned element.left— sets the left edge of a positioned box.position— sets the type of positioning for an element.right— sets the right edge of a positioned box.top— sets the top edge of a positioned box.