Search code examples
csscontainersbackground-imageopacitytransparent

Can I hide text in container until user hover over it? If yes how?


I've made a container and there is text and a background image in the container. The text is in h3 tags. I want the text to stay hidden showing only image. When user hover over the container I want to display the text and background image has to little transparent. How can I do that?? this is my CSS code so far... I have also attached the image I'm usingImage I'm using for this code

.container{
    
    background-size: cover;
    background-repeat: no-repeat;
    margin-top: 100px;
    padding: 18px 40px;
    font-size: 22px;
    text-align: center;
    width: 250px;
    height: 250px;
    border-radius: 35px;
    
    color: transparent;
    line-height: 200px;
    float: left;
    margin-left: 20%;
    background-image: url(/Unstitched.jpeg.jpg);
}
.container:hover{
    background: rgba(255,0,0,0.3) ;
    color: black
}


Solution

  • You can probably do something like this:

    .container {
      margin-top: 100px;
      padding: 18px 40px;
      font-size: 22px;
      text-align: center;
      width: 250px;
      height: 250px;
      border-radius: 35px;
      color: black;
      line-height: 200px;
      float: left;
      margin-left: 20%;
      position: relative;
    }
    
    .container::before{
      z-index: -1;
      content: '';
      position: absolute;
      inset: 0;
      margin: inherit;
      border-radius: inherit;
      background-image: url(https://i.sstatic.net/MLu3i.jpg);
      background-size: cover;
      background-repeat: no-repeat;
    }
    
    .container:hover::before {
      opacity: 0.2;
    }
    
    .container h3 {
      display: none;
    }
    
    .container:hover h3 {
      display: block;
    }
    <div class="container">
      <h3>My invisible Text</h3>
    </div>

    The relevant changes are these:

    .container h3 {
        display: none;
    }
    
    .container:hover h3 {
        display: block
    }
    

    This makes the h3 tag invisible, until someone hovers over the container element.

    Edit: From a comment on another answer I realized, that you want the image to become transparent on hover. To acheive that, you have to add the image to a separate element, otherwise the Text will be transparent too. To acheive this, I used a ::before element. Source