Search code examples
htmlcsshoveropacity

Make the div item transparent, with non-transparent content WHEN hovering


I have a <div id='a'> which becomes transparent when hovering on its parent element. But the div's content is supposed to be non-transparent. The code is following:

.changer{        
    background-color: gray;
    opacity:0;
    display: block;
    transition: .5s ease;
    backface-visibility: hidden;
}

.mb-4:hover .changer{
    opacity: 0.6;
}
<a href="#" class="d-block mb-4">
    <div id="a" class="changer d-inline">The text that must be non-transparent</div>
    <img class="img-fluid img-thumbnail" src="images/barcelona.jpg" alt="">  <!--this element is not very important-->
</a>


Solution

  • Use CSS3's background opacity to change how visible the background of a div/img/whatever is without influencing the content inside it.

    .inner {
      color: black;
      background: rgba(128, 0, 128, 0.25);
      transition: .5s ease;
      height: 3em;
    }
    
    .outer:hover .inner {
      background: rgba(128, 0, 128, 0.75);
      height: 4em;
    }
    
    .outer .inner div {
      width: 10em;
      height: 2em;
      background: gray;
    }
    
    a,
    a:visited,
    a:hover,
    a:active {
      text-decoration: none;
    }
    <a href="#" class="outer">
      <div class="inner">
        <div>Hover over me</div>
      </div>
    </a>

    EDIT

    Modified snippet to prove that the inner div isn't affected at all by changes made to the outer divs.

    EDIT 2

    To change the transparency of the text too:

    .inner {
      background: rgba(128, 128, 128, 0);
      color: rgba(0, 0, 0, 0);
      transition: .5s ease;
    }
    
    .outer:hover .inner {
      background: rgba(128, 128, 128, 1);
      color: rgba(0, 0, 0, 1);
      /* alternative: change the text color itself instead of changing opacity */
    }
    
    a,
    a:visited,
    a:hover,
    a:active {
      text-decoration: none;
    }
    <a href="#" class="outer">
      <div class="inner">Hover over me</div>
    </a>