How not to apply opacity on a child element?

8

I have a div with opacity applied, but this div has a child element. I do not want opacity to be applied to these child elements, would I have some way to solve it?

Example: link

Link code:

.div-pai{
  width: 400px;
  height: 400px;
  background-color: black;
  position: fixed;
  opacity: 0.7;
}
 .div-filho{
  width: 150px;
  height: 150px;
  position:absolute;
  top: 50%;
  left: 50%;
  background: blue;
  margin-top: -75px;
  margin-left: -75px;
  opacity: 1;
}
<div class="div-pai">
    <div class="div-filho"></div>
</div>
    
asked by anonymous 03.02.2014 / 13:32

5 answers

11

I believe it is not possible, but there are workarounds .

If you need opacity only in the background, you can apply a color rgba :

background-color: rgba(0,0,0,.7);

Fiddle . Note that IE

03.02.2014 / 13:45
3

It is not possible, the opacity of the children will always be relative to that of the parents. If you need to change just the background color, you could instead opacity. modify the background attribute:

.div-pai {width: 400px;height: 400px; position: fixed; background-color: rgba(0, 0, 0, 0.7); }
    
03.02.2014 / 13:40
2

In this case, I would advise using a .png image with background opacity on the parent element, an image of 1px per 1px repeating, is very light, some older browsers do not support this property.

    
03.02.2014 / 13:40
0

Well, it's not possible to do it the way you want it, but a suggestion is to remove div.pai and only use div.filho and put a border on it, which would result in the same thing, I would not be opaque, see the example I did in JSFiddle

I used the following CSS code:

.div-filho{
    width: 150px;
    height: 150px;
    position:absolute;
    background: blue;
    border: 150px solid rgba(0,0,0,0.75);
}

And remove div.pai from HTML.

    
03.02.2014 / 13:47
0

I've already gone through a similar case, but the Javascript Opacity is always inherited by the elements, there's no way you can remove it, so what I usually do is create an element that is exactly in the same position and dimension of the element that would be the parent with transparency, but this element is not a child, is after the transparent element and contains what would be his children.

The result can be seen in this jsfiddle .

It will be compatible with all browsers and can be applied to any element.

Example:

<div class='div_transparente'></div>
<div class='div_opaca_sem_fundo_por_cima_da_div_transparente'>
    <div class='div_filho_opaca_com_preenchimento'></div>
</div>

There are several workarounds to work around when it's background, but if your div is above an image, video, or something, I personally prefer this solution because it's generic in every case. >     

03.02.2014 / 14:12