0

In this example, I want the purple rectangle to change its opacity to 100% regardless of the value of the parent. I tried using all: unset/initial and !important but it doesn't seem to work.

.rect {
    width: 500px;
    height: 600px;
    margin-top: 200px;
    margin-left: 300px;
    background-color: black;
    /* this V */
    opacity: 37%;
    z-index: -1;
}

.rect1 {
    all: unset;
    position: absolute;
    z-index: 10;
    width: 259px;
    height: 300px;
    margin-top: 500px;
    margin-left: 50px;
    background-color: purple;
    /* to this V */
    opacity: 100% !important;
}
<div class="rect">
  <div class="rect1"></div>
</div>
Chris W.
  • 22,835
  • 3
  • 60
  • 94
Maksiks
  • 94
  • 11
  • No, you cannot do this this way - the child will be 'under the influence' of the parent's opacity. There are ways around this (e.g. using pseudo elements) but you'll need to show us enough of your HTML structure - preferably create a runnable snippet that shows the problem. See https://stackoverflow.com/help/minimal-reproducible-example – A Haworth Jun 01 '23 at 17:24

1 Answers1

1

So like Haworth pointed out, using opacity on the element itself brings all children under the influence of the pixelshading used to make the opacity effect.

If you want to get the same effect while retaining your html structure I'd recommend a different approach for the same result using RGBA or hex with an alpha channel on the background-color property directly. See example below.

body {
  height: 100%;
  width: 100%;
  background: url(https://picsum.photos/800) no-repeat;
  background-size: cover;
}

.rect {
    width: 500px;
    height: 600px;
    margin-top: 200px;
    margin-left: 300px;
    background-color: rgba(0,0,0,.37);
    /* this V
    opacity: 37%;*/
    z-index: -1;
}

.rect1 {
    position: absolute;
    z-index: 10;
    width: 259px;
    height: 300px;
    margin-top: 500px;
    margin-left: 50px;
    background-color: purple;
    /* to this V */
    opacity: 100% !important;
}
<div class="rect">
  <div class="rect1"></div>
</div>
Chris W.
  • 22,835
  • 3
  • 60
  • 94