【问题标题】:How to create a perspective shadow with CSS only?如何仅使用 CSS 创建透视阴影?
【发布时间】:2021-05-14 16:09:53
【问题描述】:

我知道 CSS 中的 box-shadow 属性,但这会产生一个看起来像是投影在元素后面的墙上的阴影。我需要创建一个看起来元素像这样站在地面上的阴影:

这是我目前所拥有的:

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>

【问题讨论】:

    标签: html css css-transforms


    【解决方案1】:

    您可以不使用元素本身的box-shadow 属性,而是使用伪元素::before 来实现此目的。

    • transform: skewX(60deg); 会让光源看起来像是来自侧面
    • height: 10%; 将使它看起来像投影在地面上
    • width: 70% 和一些定位会隐藏实际元素
    • 最后box-shadow: -25px -4px 4px 0 rgba(0,0,0,0.75); 会产生阴影

    当然,对于较旧的浏览器,您应该使用供应商前缀。

    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>

    【讨论】:

    • 等等,什么,你刚刚在第二人称的情况下回答了你自己的问题吗?
    • 我只是想share knowledge in Q&A-Style... :)
    • 哈,不错!解释清楚!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-21
    相关资源
    最近更新 更多