Box Shadows & Animation

Get a smooth animation with a 3D card effect using box shadow using just CSS animations and a pseudo element. Let’s see the final product, hover over the box below to see it:

Ok, let’s break that down. We can apply a box shadow using the box-shadow css property with the following settings:

/* offset-x | offset-y | color */
box-shadow: 60px -16px teal;

/* offset-x | offset-y | blur-radius | color */
box-shadow: 10px 5px 5px black;

/* offset-x | offset-y | blur-radius | spread-radius | color */
box-shadow: 2px 2px 2px 1px rgba(0, 0, 0, 0.2);

/* inset | offset-x | offset-y | color */
box-shadow: inset 5em 1em gold;

/* Any number of shadows, separated by commas */
box-shadow: 3px 3px red, -1em 0 0.4em olive;

So in our case, we first make a .box with rounded corners which is achieved with border-radius: 5px with a box-shadow of 0 offset-x, 1px offset-y, and 2px blur-radius, with a color of gray or rgba(0,0,0,0.15).

.box {
  position: relative;
  display: block;
  width: 100px;
  height: 100px;
  border-radius: 5px;
  background-color: #fff;
  box-shadow: 0 1px 2px rgba(0,0,0,0.15);
  transition: all 0.7s ease-in-out;
}

Next we create a pseudo element that is invisible at the beginning but when animated will receive the change. We animate the opacity because that causes the browser to do the least amount of repaints. A repaint is performed by the browser and occurs when changes are made to an elements skin that changes visibility, but do not affect its layout. You can see which css elements cause the least amount of browser adjustments here. In the pseudo element we increase the box shadow and make it invisible by giving it an opacity of 0.

.box::after {
  content: '';
  position: absolute;
  z-index: -1;
  width: 100%;
  height: 100%;
  opacity: 0;
  border-radius: 5px;
  box-shadow: 0 5px 15px rgba(0,0,0,0.3);
  transition: opacity 0.7s ease-in-out;
}

Next we need to animate the box on hover, increase the size, and make the pseudo element by changing the opacity from 0 to 1:

/* On hover, make it bigger*/
.box:hover {
  transform: scale(1.2, 1.2);
}

/* Fade in the pseudo-element with the bigger shadow */
.box:hover::after {
  opacity: 1;
}

Let’s see again for good measure 😌.

Check this box-shadow guide to read more. This was largely adapted from this guide. Check out our Codepen.

Instagram Post