【问题标题】:Add CSS inset box-shadow to parent element over the top of a child image将 CSS inset box-shadow 添加到子图像顶部的父元素
【发布时间】:2013-08-02 08:01:35
【问题描述】:

我正在尝试向父对象添加阴影,其中子 <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);
}

影子没有出现在我面前。我做错了什么?

【问题讨论】:

    标签: shadow css


    【解决方案1】:

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

    我可以想到两种可能的方法,一种是使用&lt;img&gt; 上的不透明度将其推到阴影后面,第二种方法是将嵌入的阴影放置在图像的顶部。我更喜欢第二种方法,因为可以保留图像的完全不透明度。

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

    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: "";
    }
    

    【讨论】:

    • 伪类:before只需要一个冒号
    • 对不起,如果我的评论有点苛刻,我写的时候很着急。我真的应该说是的,:before 仍然可以正常工作,但是在 CSS3 中引入了双冒号以区分 CSS 伪类(用于针对某个元素的状态)和这些 elements可以为文档的各个部分设置样式。
    • 您的评论很有帮助,不用担心,andyb ;) 再次感谢
    • 我对图像进行了变换,导致阴影不出现,所以我添加了 z-index(如果有人有同样的问题)
    猜你喜欢
    • 2015-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-03
    • 1970-01-01
    • 2021-05-19
    • 2014-02-08
    相关资源
    最近更新 更多