How does CSS opacity work?

5

Why does it work when the Padre has opacity: 1 and the Hijo-1 have opacity: 0 and NO when the Padre has opacity: 0 and Son-1 has opacity: 1 ?

The following code:

.Caja {
  width: 100px;
  height: 100px;
  background: red;
  border: 1px solid black;
  font-size: 32px;
}

.Padre {
  opacity: 1;
}

.Hijo-1 {
  opacity: 0;
}
<div class="Padre">
  <div class="Hijo-1 Caja">1</div>
  <div class="Hijo-2 Caja">2</div>
  <div class="Hijo-3 Caja">3</div>
</div>
    
asked by peruvice 09.03.2018 в 19:29
source

2 answers

5

When you apply opacity to an element, it is applied to that element and all its children elements, that is, if you hide a parent element you will never be able to see the child element. On the other hand, if you hide the child only, as the father is visible, you will still see the father even though the son is hidden (but you would not see his children).

It would be something similar to if you try to pick apples from an apple tree: if there is an apple tree, you can pick apples, but not the other way around. Here the effect is the same.

If you want to remove the background from the parent element, you could use a color rgba as background to which you can put the transparency that has that color.

Example using rgba and with a transparency of 1 on the father and 1 on the child:

.Caja {
  width: 100px;
  height: 100px;
  background: rgba(255, 0, 0, 1);
  border: 1px solid black;
  font-size: 32px;
}

.Padre {
  background: rgba(255, 255, 0, 1);
}

.Hijo-1 {
  opacity: 1;
}
<div class="Padre">
  <div class="Hijo-1 Caja">1</div>
  <div class="Hijo-2 Caja">2</div>
  <div class="Hijo-3 Caja">3</div>
</div>

Example using rgba and with a transparency of 0 on the father and 1 on the child:

.Caja {
  width: 100px;
  height: 100px;
  background: rgba(255, 0, 0, 1);
  border: 1px solid black;
  font-size: 32px;
}

.Padre {
  background: rgba(255, 0, 0, 0);
}

.Hijo-1 {
  opacity: 1;
}
<div class="Padre">
  <div class="Hijo-1 Caja">1</div>
  <div class="Hijo-2 Caja">2</div>
  <div class="Hijo-3 Caja">3</div>
</div>
    
answered by 09.03.2018 в 19:54
0

The CSS opacity property defines:

  

the transparence of an element, that is, to what degree the background is superimposed on the element.

That is, it is expected to see the background of the element that contains Padre . To achieve this, it is necessary that everything that contains Padre is also transparent in the same degree.

In the documentation in English you may find that:

  

Opacity is applied to the element as a whole, including its content, even if the value is not inherited by child elements. Therefore, the element and its secondary elements have the same opacity with respect to the background of the element, even if they have different opacities.

    
answered by 09.03.2018 в 19:49