JSFiddle - React, Tailwind, and code Playground
HTML
<div class="content" style="height: 30vh;">
some content
</div>
<div class="sticky-block">
this should stick!
</div>
<div class="content" style="height: 200vh;">
this is content
</div>
CSS
body {
margin: 0;
}
.sticky {
position: fixed;
top: 15px;
left: 0;
right: 0;
background-color: rgba(255, 200, 200, 0.5);
}
JavaScript
var $stickyBlock = document.querySelector('.sticky-block');
var origOffsetY = $stickyBlock.offsetTop - 15; // 15 is your top margin
function onScroll() {
window.scrollY >= origOffsetY ? $stickyBlock.classList.add('sticky') :
$stickyBlock.classList.remove('sticky');
}
document.addEventListener('scroll', onScroll);