将CSS插入框阴影添加到子图像顶部的父元素上

时间:2013-08-02 08:01:35

标签: css shadow css3

我正在尝试将阴影添加到父对象中,其中子<img>元素位于其中。我想要插入阴影以重叠图像。

我的HTML代码是:

<section class="highlights">
    <img src="images/hero.jpg" alt="" />
</section><!-- End section.highlights -->

和CSS:

.highlights {
    height: 360px;
    padding: 0;
    position: relative;
    overflow: hidden;
    opacity: 0.9;

    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover; 

    z-index:1;
}
.highlights img {
    height: auto;
    width: 100%;
    margin: 0 auto; 
    display: block;
    position: relative;
}

.highlights {
    -webkit-box-shadow: inset 0 0 10px 0 rgba(0, 0, 0, 0.2);
    box-shadow:  inset 0 0 10px 0 rgba(0, 0, 0, 0.2);
}

阴影不会出现在我身上。我做错了什么?

1 个答案:

答案 0 :(得分:16)

问题是图像渲染在插入框阴影的顶部。

有两种可能的方法我可以考虑这样做,一种是使用<img>上的不透明度将其推到阴影后面,另一种是将插入阴影定位在图像顶部。我更喜欢第二种方法,因为可以保留图像的完全不透明度。

注意:我已将边框设为大而红色以进行演示。

Solution 1 demo

<强> HTML

<section class="highlights">
    <img src="http://lorempixel.com/500/360/city/1/" alt=""/>
</section>

<强> CSS

.highlights {
    height: 360px;
    padding: 0;
    position: relative;
    overflow: hidden;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover; 
}
.highlights img {
    height: auto;
    width: 100%;
    margin: 0 auto; 
    display: block;
    opacity: .9;
}
.highlights {
    -webkit-box-shadow: inset 0 0 10px 0 rgba(0, 0, 0, 0.2);
    box-shadow: inset 0 0 25px 25px red;
}

Solution 2 demo

<强> CSS

.highlights {
    height: 360px;
    padding: 0;
    position: relative;
    overflow: hidden;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover; 
}
.highlights img {
    height: auto;
    width: 100%;
    margin: 0 auto; 
    display: block;
}
.highlights::before {
    -webkit-box-shadow: inset 0 0 10px 0 rgba(0, 0, 0, 0.2);
    box-shadow: inset 0 0 25px 25px red;
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    content: "";
}
相关问题