How to animate div or card with shadow - Two best method

⁕ Animating a changed box-shadow (in this case from box-shadow: 0 1px 2px rgba(0,0,0,0.15) to box-shadow: 0 5px 15px rgba(0,0,0,0.3) causes a re-paint on every frame.

This is an easy way and your desktop likely handles it without any issues, but your phone may not, and even your desktop may suffer when animating a more complex layout.


⁕ We can minimize the number of repaints by inserting a pseudo-element with :after, adding a shadow to that element, and then animating the opacity of the pseudo-element on hover.

Changes to both the transform and opacity properties are hardware accelerated, and we can achieve better performance when sticking to only changing these properties in animations.


Crete an element as you like.

I created three div here just for example.


Method-1: Animate the box-shadow property

Demo
Hover the cards
CSS for Method-1
.item-1{
    box-shadow:0 1px 2px rgba(0,0,0,0.15);
    -webkit-transition:all .6s 
    cubic-bezier(0.165, 0.84, 0.44, 1);
    transition:all .6s cubic-bezier(0.165, 0.84, 0.44, 1)
}

.item-1:hover,.item-1:active{
    box-shadow:0 5px 15px rgba(0,0,0,0.3);
    -webkit-transform:scale(1.25, 1.25);
    transform:scale(1.25, 1.25);
}
        

Method-2: Animate a pseudo-element

Demo
Hover the cards This is better than Method-1
CSS for Method-2
.item-a{
 box-shadow:0 1px 2px rgba(0,0,0,0.15);
 position:relative;
 border-radius:5px;
 -webkit-transform:translateY(0);
 -webkit-transition:all .6s cubic-bezier(0.165, 0.84, 0.44, 1);
 transition:all .6s cubic-bezier(0.165, 0.84, 0.44, 1)
}

.item-a:after{
 content:"";
 border-radius:5px;
 position:absolute;
 top:0;
 left:0;
 width:100%;
 height:100%;
 box-shadow:0 5px 15px rgba(0,0,0,0.3);
 opacity:0;
 -webkit-transition:all .6s cubic-bezier(0.165, 0.84, 0.44, 1);
 transition:all .6s cubic-bezier(0.165, 0.84, 0.44, 1);
}

.item-a:hover:after{
 opacity:1;
}

.item-a:hover{
 -webkit-transform:scale(1.25, 1.25);
 transform:scale(1.25, 1.25);
}
        

Comments

Popular Posts