htmlcssparent

How to override parent's styles in css?


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>


Solution

  • 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>