如何使用CSS实现弯曲的阴影效果?

时间:2019-04-01 06:51:13

标签: css3

我正在尝试使用CSS实现以下投影效果:

enter image description here

我尝试将具有线性渐变的<hr>元素设置为背景图像,作为在图像上使用box-shadow规则的替代方法,但是它不会产生所需的弯曲阴影效果。

我仅通过CSS就能做到吗?

这是我当前的代码:

HTML

<section class="section-categories section-fruits">
    <div class="row">
        <figure class="categories">
            <img src="res/img/category/fruits.png" alt="Offers" class="categories__fruits">
        </figure>
        <div class="categories__explore">
            <p>Fruits & Vegetables</p>
            <p>A variety of fresh fresh and vegetables</p>
            <button>Explore fruit and veg</button>
        </div>
    </div>
</section>

CSS

/* Using Box Shadow, but didn't get the desired effect */    
.section-categories{
    height: 250px;
    margin: 20px 0px;
    box-shadow: 0px 1px 1px rgba(0,0,0,0.3);
}

1 个答案:

答案 0 :(得分:2)

一种纯CSS方法可能是在伪元素上使用radial-gradient函数,如下所示:

/* The shadow CSS class element */
.shadow {
  position:relative;
}

/* The CSS peseudo element that achieves the shadow effect */
.shadow:after {
  content:'';
  display:block;
  position:absolute;
  bottom:-1rem;
  /* The main idea with this technique is to use a radial gradient to simulate the 
  desired effect */
  background:radial-gradient(farthest-corner at 50% 0px, grey 0%, transparent 50%);
  width:100%;
  height:1rem;
  
}

/* The styling below is not part of the technique and is included to support the snippet */
div {
  display:flex;
  flex-direction:row;
  justify-content:center;
  align-items:center;
}

div button {
  background:red;
  
}
<div class="shadow">
<img src="https://i.pinimg.com/originals/2b/1c/f5/2b1cf5525873467315eaa0c07394d302.jpg" height="100px" />
<button>Explore</button>
</div>

这里的想法是定义一个伪元素:after,即投射阴影的实际元素(即上面的片段中的<div>),其中包含一个radial-gradient。为了模拟所需的效果,radial-gradient的内部和外部呈深色,其渐变的中心通过farthest-corner at 50% 0px参数偏移到伪元素的上边缘。

希望有帮助