Css Sticky multiple sticky elements
by wamosjk
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/stickyfill/1.1.4/stickyfill.min.js"></script>
<header>Header</header>
<div class="content">
<div class="row">
<div class="col-span-2">Left Div</div>
<div class="col-span-8">
<div class="main-content">Main Content</div>
</div>
<div class="col-span-2">
<div class="sticky-container">
<div class="sticky-box">
Sticky Box
</div>
</div>
<div class="info">Info Div</div>
<div class="sticky-container">
<div class="sticky-box">
Sticky Box
</div>
</div>
<div class="info">Info Div</div>
<div class="sticky-container" id="last-sticky-container">
<div class="sticky-box">
Sticky Box
</div>
</div>
<div class="info">Info Div</div>
</div><!--End col-span-2 -->
</div><!--End Row-->
</div><!--End Content-->
<footer>Footer</footer>
CSS
body{padding:0;margin:0;}
header, footer{
background:blue;
color:#fff;
padding:20px;
text-align:center;
}
header{height:200px;}
footer{height:1000px;}
.content {
max-width: 1080px;
margin: 0 auto;
}
/*the following is a clearfix for containing floated elements*/
.row:after {
content: ".";
visibility: hidden;
display: block;
height: 0;
clear: both;
}
.col-span-2, .col-span-8{
float:left;
min-height:1px;
}
.col-span-2{
width:20%;
}
.col-span-8{
width:60%;
}
.sticky-container{
height:450px;
position:relative;
}
.sticky-box{
position: -webkit-sticky;
position: sticky;
/*the following is how far from the top of the screen you want your element to stick if you change it to 20px it will start to stick 20px from the top of the screen*/
top: 0;
}
.main-content{height:2350px;background:#333;color:#fff;text-align:center;}
.info{background:#888;height:200px;color:#fff;}
.sticky-box{background:red;height:100px;color:#fff;}
JavaScript
var stickyElements = document.getElementsByClassName('sticky-box');
for (var i = stickyElements.length - 1; i >= 0; i--) {
Stickyfill.add(stickyElements[i]);
}