EN
CSS - top sticky position for div element
11
points
In this short article, we would like to show how to use sticky top
positioning with pure CSS.
In practice, we can use it to keep the item header visible during scrolling.
To enable sticky positioning
position: sticky
and one of the:top
,left
,right
orbottom
property is needed.In the article we will use
top
one.
How sticky works?
It glues the element depending of
top
,left
,right
orbottom
property - it do not let the element to disappear during scrolling usingfixed
position
when element border touches bound set by the property (top
,left
, etc.).
Simple example:
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<head>
<style>
body {
max-height: 300px;
}
div.header {
position: -webkit-sticky; /* <----- required (for WebKit) */
position: sticky; /* <------------- required */
top: 10px; /* <-------------------- required */
border: 1px solid red;
background: silver;
}
div.content {
border: 1px solid orange;
height: 1000px;
}
</style>
</head>
<body>
<p>Some text here...</p>
<div>
<div class="header">Item 1</div>
<div class="content">
Some text here...<br />
Some text here...<br />
Some text here...<br />
Some text here...<br />
</div>
</div>
<p>Some text here...</p>
<p>Some text here...</p>
<p>Some text here...</p>
</body>
</html>