Home > Net >  Add shadow to sticky element
Add shadow to sticky element

Time:12-26

I am new to css and html and I am trying to recreate the behavior enter image description here whereby a group is sticky and once it is sticky I add a bottom shadow. I manage to make the element sticky by applying this code:

<style>
#sticky-top {
    position: sticky;
    top: 0px;
    z-index: 9999
    }
</style>

but now I dont know where to start to add the shadow only when the group is stuck at the top. do you have an idea? thanks

CodePudding user response:

To add a shadow to the sticky element, you can use the box-shadow property in your CSS. Here is an example:

<style>
#sticky-top {
    position: sticky;
    top: 0px;
    z-index: 9999;
    box-shadow: 0px 0px 5px 0px rgba(0,0,0,0.75);
}
</style>

This will add a 5px wide shadow to the bottom of the element with an opacity of 0.75. You can adjust the values to change the size and intensity of the shadow.

Alternatively, if you only want to add the shadow once the element becomes sticky, you can use JavaScript to add a class to the element when it becomes sticky, and then apply the shadow to that class:

<style>
.sticky-shadow {
    box-shadow: 0px 0px 5px 0px rgba(0,0,0,0.75);
}
</style>
<script>
var stickyElement = document.getElementById('sticky-top');
window.addEventListener('scroll', function() {
    if (window.pageYOffset >= stickyElement.offsetTop) {
        stickyElement.classList.add('sticky-shadow');
    } else {
        stickyElement.classList.remove('sticky-shadow');
    }
});
</script>

This will add the sticky-shadow class to the element when it becomes sticky, and remove it when it is no longer sticky, allowing you to apply the shadow only when necessary.

  • Related