Opacity bleeding into child divs

后端 未结 2 880
孤独总比滥情好
孤独总比滥情好 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 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;
    }

    RGBA

    Some Text

    Some more text



    OPACITY

    Some Text

    Some more text



提交回复
热议问题