11

I want apply opacity for parent but I do not want the child element to inherit this opacity.

<div class="parent">
 <div class="child"></div>
</div>

.parent {
  opacity: 0.6;
}

Is there a way to "cancel" the inherited opacity? maybe force it to opacity=1for the child element?

Adriano
  • 19,463
  • 19
  • 103
  • 140
khanh
  • 4,516
  • 10
  • 29
  • 48
  • look at http://stackoverflow.com/questions/806000/transparent-background-but-not-the-content-text-images-inside-it-in-css-on – Adriano Feb 27 '14 at 08:46

2 Answers2

11

The opacity of the child will always be the opacity of the parent if the opacity of the child is 1.

This is not a problem with inheritance, but rather with the way opacity is calculated.

For instance,

<div id="parent">
    <div></div>
</div>

<div id="original">
</div>

<div id="quarter">
</div>

#parent div, #quarter {
    width: 100px;
    height: 100px;
    background-color: orange;
}

#parent div {
    opacity: 0.5;
}

#parent {
    opacity: 0.5;
}

#quarter {
    opacity: 0.25;
}

#quarter's opacity, from your perspective, is the same as that of #parent div, but in actual fact, #parent div has twice the opacity of #quarter. See this jsfiddle for more detail: http://jsfiddle.net/HUaNm/


The only way to avoid this is to move the child out of the parent. Alternatively, depending on what you want here, you can also use rgba colors for the background/border/font color of the parent instead of opacity, but the effect is not the same as applying opacity.

Adriano
  • 19,463
  • 19
  • 103
  • 140
Yi Jiang
  • 49,435
  • 16
  • 136
  • 136
  • 8
    This was driving me nuts. If only the browsers would support opacity:1.5 or some other way to over reference this would be a non issue. – Pow-Ian Oct 24 '12 at 15:17
0

if you have parent background color - use RGBA, if you have parent image - use additional RGBA layer between parent and child divs playing with css position.