Opacity bleeding into child divs

后端 未结 2 846
孤独总比滥情好
孤独总比滥情好 2021-01-24 02:27

I have nested div tags, and the idea is that the outer one contains a background picture, and then the inner ones have text over them. I\'d like to change the opacity on the bac

相关标签:
2条回答
  • 2021-01-24 02:47

    what you are trying to do cannot be done since nested divs will inherit the opacity property and it cannot be overridden

    and because you want a background-image and not a background-color the use of rbga() is not useful in this case

    so the best way i see it to use and transparent background image (gif, png) and let work that way.

    0 讨论(0)
  • 2021-01-24 03:02

    whenever you don't want to apply the opacity to inner child use instead rgba on background-color.

    why?

    because in opacity according to MDN

    The value applies to the element as a whole, including its contents, even though the value is not inherited by child elements. Thus, an element and its contained children all have the same opacity relative to the element's background, even if the element and its children have different opacities relative to one another.

    So, see snippet below with differences:

    /*SNIPPET ONLY*/
    
    * {
      margin: 0;
      padding: 0
    }
    body {
      background-color: green
    }
    .container {
      background-color: red;
      border: 1px solid yellow
    }
    /*GENERAL*/
    .myBackgroundDivs {
      text-align: center;
      width:500px;
      margin:auto
    }
    
    /*RGBA*/
    .rgba .myBackgroundDivs {
      background: url('http://www.lorempixel.com/500/500') no-repeat fixed center / cover;
    
    }
    .rgba .myTextDivs {
      background-color: rgba(255,255,255,.4)
    }
    /*OPACITY*/
    .opacity .myBackgroundDivs {
      background: url('http://www.lorempixel.com/500/500') no-repeat fixed center / cover;
      opacity:.4;
    }
    .opacity .myTextDivs {
      opacity: 1;
    }
    <h1>RGBA</h1>
    <div class="container rgba">
      <div class="jumbotron myBackgroundDivs">
        <div class="myTextDivs">
          <h1>Some Text</h1>
          <h3>Some more text</h3>
          <br>
          <br>
        </div>
      </div>
    </div>
    <h1>OPACITY</h1>
    <div class="container opacity">
      <div class="jumbotron myBackgroundDivs">
        <div class="myTextDivs">
          <h1>Some Text</h1>
          <h3>Some more text</h3>
          <br>
          <br>
        </div>
      </div>
    </div>

    0 讨论(0)
提交回复
热议问题