CSS: using sticky positioning
Two properties are usually required for sticky positioning behavior: position
set to sticky
and top
set to the desired offset, e.g. .5em
, when the element is ‘sticking’ to the top of the viewport or nearest relative container.
Code
<style>
#sticky-1-wrapper {
position: relative;
overflow: scroll;
height: 200px;
}
#sticky-1-wrapper * {
border: 2px solid gray;
padding: 1em;
}
#sticky-1-grid {
display: grid;
grid-template-columns: 1fr 1fr;
}
#sticky-1-height-setter {
height: 400px;
}
#sticky-1-sticky {
position: -webkit-sticky;
position: sticky;
top: .5em;
height: 3.5em;
}
#sticky-1-footer {
height: 140px;
background-color: #333;
color: #ccc;
}
</style>
<div id='sticky-1-wrapper'>
<div id='sticky-1-header'>Header</div>
<div id='sticky-1-grid'>
<div id='sticky-1-height-setter'>Content</div>
<div id='sticky-1-sticky'>position:sticky; top:.5em;</div>
</div>
<div id='sticky-1-footer'>Footer</div>
</div>
Result
Header
Content
position:sticky; top:.5em;
For the most part, this feature is supported by the major browsers. As shown in the example, for Safari the prefix position: -webkit-sticky;
is required.