How to create a perspective shadow with CSS only?

只谈情不闲聊 提交于 2019-12-10 10:49:02

问题


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:

This is what I have so far:

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

回答1:


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(//placehold.it/150x150);
  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>


来源:https://stackoverflow.com/questions/40357225/how-to-create-a-perspective-shadow-with-css-only

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!