Search code examples
htmlcssopacity

How to apply an opacity without affecting a child element with html/css?


I want to achieve this using html and css:

schema

I have tried to set the opacity of the container to 0.3 and the box to 1, but it doesn't work: both divs have 0.3 opacity.

jsFiddle of my try here

The effect I am trying to achive is a popup box that comes on top of the page. It is highlighted by fading the content below (by lowering the opacity).


Solution

  • As far as I know you can't do it in a simple way. There a couple of options here:

    1. Use absolute positioning to position box "inside" the container.

      #container {
          opacity: 0.3;
          background-color: #777788;
          position: absolute;
          top: 100px;
          left: 100px;
          height: 150px;
          width: 300px;
      }
      #box {
          opacity: 1;
          background-color: #ffffff;
          position: absolute;
          top: 110px;
          left: 110px;
          height: 130px;
          width: 270px;
      }
      <div id="container"></div>
      <div id="box">
          <p>Something in here</p>
      </div>

    2. Use Javascript - almost the same as above, but position and size don't have to be hardcoded.