Search code examples
javascriptjqueryhtmlcssopacity

Overlapped elements with opacity and handling the 'hover' on those


This is a Q/A on how to handle the opacity of overlapping elements and make it consistent while hover, with a JS solution.

Requirement

The requirement is to develop two elements, which are transparent and overlapping, like the two red boxes below. These need to be transparent so that the background contents are visible.

enter image description here

Now, while hover on any of these elements, the particular element should turn opaque like below.

enter image description here


Solution

  • There's a CSS only solution, which makes it a bit more efficient. Like this for example:

    body {
      background-image: linear-gradient(45deg, transparent 50%, #aaa 75%);
      background-size: 20px 20px;
    }
    
    #a {
      position: absolute;
      width: 150px;
      height: 150px;
      top: 50px;
      left: 50px;
      background: rgba(255, 0, 0, 1);
    }
    
    #b {
      position: absolute;
      width: 150px;
      height: 150px;
      top: 125px;
      left: 125px;
      background: rgba(255, 0, 0, 1);
    }
    
    #wrapper {
      opacity: 0.5;
    }
    
    /* instead of changing the classes,  
    you can use selectors like this:*/
    
    #wrapper:hover #a:hover,
    #wrapper:hover #b:hover {
      opacity: 1;
      z-index: 10;
    }
    
    #wrapper:hover {
      opacity: 1;
    }
    
    #wrapper:hover #b,
    #wrapper:hover #a {
      opacity: 0.5;
      z-index: -1;
    }
    <div id=wrapper>
      <div id="a">
      </div>
      <div id="b">
      </div>
    </div>