Home > Software engineering >  I want to stack two DIVs on top of each other and have one be transparent so you can see through to
I want to stack two DIVs on top of each other and have one be transparent so you can see through to

Time:10-21

I have a background image inside a div and I want to be able to place another black box on top of the background image with a lower opacity so that you can see through it and it will darken the image.

CodePudding user response:

You can use z-index on an image in a container to push it to the back of the div to act as a background-image by giving it a z-index of -1 and the parent a z-index of 1. Then position it absolute and use it to fill the whole parent.

An implementation is here below:

**My index.html **

<div class="container">
    <div class="content">
        <img src="./images/img.jpg" alt="">
        <h1>My content</h1>
    </div>
</div>

**My style.css **

.container {
    position: relative;
    display: grid;
    place-content: center;
    z-index: 1;
}
.container .content {
    width: 100%;
    height: 100%;
    background-color: #00000052;
}
.container img {
    position: absolute;
    z-index: -1;
    width: 100%;
    height: 100%;
    object-fit: cover;
}

CodePudding user response:

The easiest way to accomplish this effect is by applying the CSS brightness filter directly on the image.

You could certainly stack two divs on top of each other with absolute/relative positioning and z-index, but those can create other issues and will require you to write more code for less performance.

.dark {
  filter: brightness(40%);
}
<img src="https://randomuser.me/api/portraits/women/68.jpg" width="200" height="200" alt="" />

<img class="dark" src="https://randomuser.me/api/portraits/women/68.jpg" width="200" height="200" alt="" />
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related