I do not want to inherit the child opacity from the parent in CSS

前端 未结 14 925
猫巷女王i
猫巷女王i 2020-11-21 06:31

I do not want to inherit the child opacity from the parent in CSS.

I have one div which is the parent, and I have another div inside the first div which is the child

相关标签:
14条回答
  • 2020-11-21 07:03

    It seems that display: block elements do not inherit opacity from display: inline parents.

    Codepen example

    Maybe because it's invalid markup and the browser is secretly separating them? Because source doesn't show that happening. Am I missing something?

    0 讨论(0)
  • 2020-11-21 07:05

    Assign opacity 1.0 to the child recursively with:

    div > div { opacity: 1.0 }
    

    Example:

    div.x { opacity: 0.5 }
    div.x > div.x { opacity: 1.0 }
    <div style="background-color: #f00; padding:20px;">
      <div style="background-color: #0f0; padding:20px;">
        <div style="background-color: #00f; padding:20px;">
          <div style="background-color: #000; padding:20px; color:#fff">
             Example Text - No opacity definition
          </div>
        </div>  
      </div>
    </div>
    <div style="opacity:0.5; background-color: #f00; padding:20px;">
      <div style="opacity:0.5; background-color: #0f0; padding:20px;">
        <div style="opacity:0.5; background-color: #00f; padding:20px;">
          <div style="opacity:0.5; background-color: #000; padding:20px; color:#fff">
            Example Text - 50% opacity inherited
          </div>
        </div>  
      </div>
    </div>
    <div class="x" style="background-color: #f00; padding:20px;">
      <div class="x" style="background-color: #0f0; padding:20px;">
        <div class="x" style="background-color: #00f; padding:20px;">
          <div class="x" style="background-color: #000; padding:20px; color:#fff">
             Example Text - 50% opacity not inherited
          </div>
        </div>  
      </div>
    </div>
    <div style="opacity: 0.5; background-color: #000; padding:20px; color:#fff">
      Example Text - 50% opacity
    </div>

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