Search code examples
htmlcsscss-transforms

How to create a perspective shadow with CSS only?


I know about the box-shadow property in CSS, but this produces a shadow that looks like being projected on a wall right behind the element. I need to create a shadow that looks like the element is standing on the ground like this:

enter image description here

This is what I have so far:

div {
  display: inline-block;
  height: 150px;
  width: 150px;
  background: url(https://via.placeholder.com/150);
  margin-left: 20px;
  box-shadow: -5px 5px 10px 0 rgba(0,0,0,0.75);
}
<div></div>
<div></div>


Solution

  • You can achieve this without using the box-shadow property on the element itself, but on the pseudo element ::before.

    • transform: skewX(60deg); will make it look like the light source is coming from the side
    • height: 10%; will make it look like projected on the ground
    • width: 70% and some positioning will hide the actual element
    • And at last box-shadow: -25px -4px 4px 0 rgba(0,0,0,0.75); will produce the shadow

    Of course for older browsers you should use vendor prefixes.

    div {
      position: relative;
      display: inline-block;
      height: 150px;
      width: 150px;
      background: url(https://via.placeholder.com/150);
      margin-left: 30px;
    }
    div::before {
      content: "";
      position: absolute;
      z-index: -1;
      bottom: 0;
      left: 15px;
      height: 10%;
      width: 70%;
      box-shadow: -25px -4px 4px 0 rgba(0,0,0,0.75);
      transform: skewX(60deg);
    }
    <div></div>
    <div></div>