I needed a fixed section in a site, that will scroll with you for while on the page. The key point here is that it needed to scroll for a certain amount, not permanently.
Mostly it was to make sure that the visitors don’t accidentally scroll away without interacting with that section because it had a nice presentation for some products/solutions.
Our idea was to place that fixed section into a wrapper section and have it scroll for the amount of height the parent has.
Since position: sticky works with a parent, and doesn’t mess with the entire page that was the perfect solution for us.
We started with 2 div elements.
<main>
<div class="dm-fixed-wrap-main">
<div class="dm-fixed-wrap">
Your Content goes here
</div>
</div>
</main>
The parent needs to be position: relative, while the child will be sticky to create the effect on scroll.
.dm-fixed-wrap-main {
position: relative;
.dm-fixed-wrap {
position: sticky;
top: 60px;
}
}
Now comes the part on making the parent height bigger so it will scroll inside the parent div, giving the impression that the element is sticky on the screen for a while, until you scroll past it.
To do this we’ll use a few lines of JS. In the code example from below, we set the parent height to be 1.7 times the child on smaller screens and 1.4 on bigger screens.
This is totally up to you if you need different sizes for mobile and desktop, or how do you want to determine the height of the parent.
And we also run it with a timeout of 500ms, making sure the child will render completely. Since it wasn’t on the initial view when loading the page, this didn’t affect the user experience.
setTimeout(function() {
if ($(window).width() < 790) {
var height = $('.dm-fixed-wrap').height() * 1.7;
} else {
var height = $('.dm-fixed-wrap').height() * 1.4;
}
$('.dm-fixed-wrap-main').height(height);
}, 500);
Feel free to make the JS code prettier.
The final product will be something like the image below. The ratios are a bit exaggerated.