How to prevent sticky element from affecting height of next element?

46 Views Asked by At

I'm currently working on a web project where I have a sticky element positioned on the page. However, I'm encountering an issue where the sticky element seems to affect the height of the next element when it becomes sticky. Is there a way to prevent this behavior?

I've tried various CSS properties and approaches, such as setting position: sticky and adjusting margins and paddings, but haven't found a satisfactory solution yet. Ideally, I'd like the sticky element to maintain its position without causing any layout shifts or affecting the height of subsequent elements.

Any insights or suggestions on how to achieve this would be greatly appreciated. Thank you!

In attempting to resolve the issue with the sticky element affecting the height of the following element, I've experimented with various CSS properties and adjustments. Primarily, I've applied position: sticky to the sticky element and have adjusted its margins and paddings to see if it alleviates the problem.

My expectation was that by using position: sticky, the element would maintain its position relative to the viewport and not affect the layout of other elements on the page. Additionally, I anticipated that adjusting margins and paddings might help create space around the sticky element, further preventing it from influencing the height of subsequent elements.

However, despite these efforts, I still encounter the issue where the sticky element seems to impact the height of the next element. I'm seeking insights or alternative approaches to effectively prevent this behavior while maintaining the sticky positioning of the element.

1

There are 1 best solutions below

1
Hari Vishnu G On

$(window).on("load resize",function(){
    if (window.innerWidth > 991) {
        let titleHeight = parseFloat($(".empower-title h2").height()) + parseFloat($(".empower-title").css("top").replace('px', '')) + parseFloat($(".empower-title h2").css("margin-bottom").replace('px', ''));
        $('.sticky-cards>div').each(function(index) {
            $(this).css('top', titleHeight + (index * 10) + 'px');
        });
    } else {
        $(".zwc-scroll-tab").css("top", "0px");
    }
});
$(window).scroll(function () {
    let height = parseFloat($(".empower-title h2").height()) + parseFloat($(".empower-title h2").css("margin-bottom").replace('px', '')) + $(".zwc-scroll-tab:last-child()").height();
    if (window.innerWidth > 991) {
        if ($(".zwc-empower-scroll").offset().top + 1000 < $(window).scrollTop()) {
            $(".empower-title").css("height", height);
        } else {
            $(".empower-title").css("height", "auto");
        }
    } else {$(".empower-title").css("height", "auto");}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>