JSFiddle - React, Tailwind, and code Playground
by Ahmad Baktash Hayeri
HTML
<div class="parent">
<div class="child"></div>
</div>
<div class="placeholder"></div>
CSS
.parent{
width:100%;
height: 1300px;
background: green;
position:relative;
}
.child{
position:absolute;
width:200px;
height:200px;
background: yellow;
}
.placeholder{
height:400px;
width:100%;
background:gray;
}
.fixed{
position: fixed;
}
.absolute{
position:absolute;
}
JavaScript
$(function(){
$(window).scroll(function(){
if($(this).scrollTop() >= 0 && $(this).scrollTop() < ($('.parent').height() - $('.child').height())){ $('.child').removeClass('absolute').addClass('fixed').css('top', '1rem');
} else {
$('.child').removeClass('fixed').addClass('absolute').css('top', $('.parent').height() - $('.child').height());
}
});
});