amanda45 amanda45 - 5 months ago 13
CSS Question

Prevent element from inheriting parent's opacity

I am working on a webpage and I want to put a button on a transparent div that shows the background image. When I place a button it is also transparent. How can I make it not transparent?



div.background {
background: url(klematis.jpg) repeat;
border: 2px solid black;
}
div.transbox {
margin: 30px;
background-color: #ffffff;
border: 1px solid black;
opacity: 0.6;
filter: alpha(opacity=60); /* For IE8 and earlier */
}
div.transbox p {
margin: 5%;
font-weight: bold;
color: #000000;
}

<div class="background">
<div class="transbox">
<p>This is some text that is placed in the transparent box.</p>
<input type="button" value="Ok">

</div>
</div>




Answer

Use the rgba() color method instead of opacity:

div.background {
  background: url(klematis.jpg) repeat;
  border: 2px solid black;
}
div.transbox {
  margin: 30px;
  background-color: rgba(255, 255, 255, 0.6);
  border: 1px solid black;
}
div.transbox p {
  margin: 5%;
  font-weight: bold;
  color: #000000;
}
<div class="background">
  <div class="transbox">
    <p>This is some text that is placed in the transparent box.</p>
    <input type="button" value="Ok">
  </div>
</div>

With opacity, the effect applies to the entire element, including child elements and content.

From MDN:

[Opacity] 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.

The exception to this rule is background-color set with rgba().

The rgba() color model allows for the opacity to be set via the alpha channel.

So you could set the parent to div { background-color: rgba (255, 255, 255, 0.6); }, and that would set the opacity to 0.6 on the background-color alone. Child elements would be unaffected.

Learn more here: A brief introduction to Opacity and RGBA

For opacity and images see: