Search code examples
htmlcssmousehover

Using mouse hover function to hide and show in the same position


I have a problem to do the mouse hover function to hide and show in the same position with two pictures. For example, if I hover over the picture, the second picture will stay in the first picture position and the size is the same as the first picture.

Below is my sample coding:

<style>
.preview-image {
  background-size: 0 0;
  width: 100vw;
}
.nopadding {
  padding: 0!important;
} 
.container:hover .preview-image {
  opacity: 1;
  background-repeat: no-repeat;
  background-size: cover;
  height: 100px;
}
.container:hover .txt-container {
  opacity: 0;
}
.txt-container {
  opacity: 1;
  font-weight: bold;
  color: black;
}
.btn {
  background-color: #4CAF50;
  color: white;
  font-size: 16px;
  padding: 16px 32px;
}
</style>
 <ul class="nopadding">
<div class="container">
    <li class="preview-image" style="background-image:url(https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTadW0C0MkeampnVW-_sT7bMOemD3roUI5x-w&usqp=CAU);">
      <div class="txt-container">
          <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQXV2n5aZGMr6SoY-thS3xR6bPchCnUu23SiA&usqp=CAU" />
      </div>
    </li>
  </div>
</ul>

For example - if no hover, the first picture will show on the page:

img1

For example - if hover to the first picture, the second picture will overlay with the first page and size maintain the same with the first picture on the page:

img2

Hope someone can guide me on how to solve it. Thanks.


Solution

  • Try the one below to control the display property of two images.

    Also I have made the txt-container class to an inline-block elemment to make the div fit with the images.

    .nopadding {
      padding: 0 !important;
    }
    .txt-container .image-one {
      display: none;
    }
    .txt-container .image-two {
      display: block;
    }
    .txt-container:hover .image-one {
      display: block;
    }
    .txt-container:hover .image-two {
      display: none;
    }
    
    .txt-container {
      font-weight: bold;
      color: black;
      display: inline-block;
    }
    
    .btn {
      background-color: #4CAF50;
      color: white;
      font-size: 16px;
      padding: 16px 32px;
    }
    <ul class="nopadding">
      <div class="container">
        <li class="preview-image">
          <div class="txt-container">
            <img
              class="image-one"
              src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTadW0C0MkeampnVW-_sT7bMOemD3roUI5x-w&usqp=CAU" alt="">
            <img
              class="image-two"
              src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQXV2n5aZGMr6SoY-thS3xR6bPchCnUu23SiA&usqp=CAU" />
          </div>
        </li>
      </div>
    </ul>