Kreha Kreha - 1 year ago 62
Sass (Sass) Question

Place background behind img in div

So, I have img inside div like this:

<div class="row text-center about__gallery">
<div class="col-xs-12 col-sm-4">
<div class="about__gallery--first img">
<img />
</div>
</div>
.
.
.
</div>


The effect I want to achieve is to have div with color exactly the same size as img behind it (on hover I'm gonna move img a little bit).
SCSS looks like this:

.about__gallery{
margin-top: 5%;
.img{
background-repeat:no-repeat;
background-size:cover;
width:70%;
height:230px;
margin-bottom: 15%;
img{
z-index: 3;
}
&:before {
position: absolute;
content: " ";
display: block;
width: 70%;
height: 230px;
background-color: $color-blue;
z-index: -100;
}
}
.about__gallery--first{
margin-left: 45%;
img{
content:url("../img/aboutus_pic1.png");
width: 100%;
}
}
.
.


Unfortunately result looks like this: IMAGE

Answer Source

A few things I would do. First, remove the static height/widths that you have set. Let the container inherit them from the image. Then, you'll need to set the top/left position of the pseudo element, relative to the position of your container (which should be set to relative). Here's a working example.

<div class="row text-center about__gallery">
    <div class="col-xs-12 col-sm-4">
        <div class="about__gallery--first img">
            <img src="http://placehold.it/250x250" />
        </div>
    </div>
</div>

.about__gallery {
    margin-top: 5%;

    .img {
        position: relative;
        margin-bottom: 15%;

        img {
            opacity: 0.8; // just to show the blue behind it
            width: 100%; 
            height: auto;
        }

        &:before {
            position: absolute;
            top: 0;
            left: 0;
            content: " ";
            display: block;
            width: 100%;
            height: 100%;
            background-color: $color-blue;
            z-index: -100;
        }
    }

    &--first {
        margin-left: 45%;
    }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download