Caspert
Caspert

Reputation: 4363

Add CSS inset box-shadow to parent element over the top of a child image

I'm trying to add shadow to the parent object where an child <img> element is positioned inside it. I wan the inset shadow to overlap the image.

My HTML code is:

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

and 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);
}

The shadow is not appearing for me. What did I do wrong?

Upvotes: 11

Views: 16407

Answers (1)

andyb
andyb

Reputation: 43823

The problem is that the image is rendered over the top of the inset box-shadow.

There are 2 possible ways I can think of doing this, one using opacity on the <img> to push it behind the shadow and the second way to position the inset shadow over the top of the image. I prefer the second approach because the full opacity of the image can be retained.

Note: I have made the border large and red for demonstration.

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

Upvotes: 23

Related Questions