Search code examples
htmlcssimagehoveroverlay

CSS Image not scaling on hover


I've made a responsive image grid and am trying to add a hover effect to it so that the image gets a dark overlay and some text fades in on it. However, I've been having a tough time implementing it.

Here's my HTML structure.

<div class="tile">
        <img src="some_image" class="animate">
        <div class="overlay">
        <p>Mahatma Gandhi</p>
</div>

And here's my CSS

.gallery .row .tile:hover ~ .tile img {
  transform: scale(1.2);
}

However upon hovering over the image, it does not have the expected behaviour.

What's wrong?

EDIT I got the hover effect to work and I can now fade in text.

Here's my code for that:

<div class="tile">
                        <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/d/d6/Tagore_Gandhi.jpg/220px-Tagore_Gandhi.jpg" class="animate">
                        <div class="overlay">
                                <div class="text">Mahatma Gandhi</div>
                            </div>
                      </div>

CSS

.tile {
  position: relative;
  width: 100%;
}

.image {
  display: block;
  width: 100%;
  height: auto;
}

.overlay {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  height: 100%;
  width: 100%;
  opacity: 0;
  transition: .5s ease;
  background-color: rgba(0, 0, 0, 0.8);
}

.tile:hover .overlay {
  opacity: 1;
}

This seems to work but I think it doesnt have a certain "feel" to it. So I need to add a scale effect to the image. How can I do that


Solution

  • Here is a jsFiddle that i think will help you to resolve your issue: https://jsfiddle.net/mcs3yn1x/

    HTML

    <div class="tile">
     <img src="https://picsum.photos/200/300" class="animate">
     <div class="overlay">
     <p>Mahatma Gandhi</p>
    </div>
    

    CSS

    .tile {
      border: 2px solid black;
    }
    
    .tile:hover img {
      transform: scale(1.2);
    }
    

    Edit

    After hearing alittle more about your issue I have created the following jsFiddle: https://jsfiddle.net/f1gzonjr/4/

    HTML

    <div class="tile">
      <div class="container">
       <img src="https://picsum.photos/200/300" class="animate">
       <div class="overlay">
        <p>Mahatma Gandhi</p>
      </div>
    </div>
    

    CSS

    .tile {
      position: relative;
    
      top: 0px;
      left: 0px;
    
      height: 300px;
      width: 200px;
    
      overflow: hidden;
    
      border: 2px solid black;
    } 
    
    .container:hover img{
      transform: scale(1.2);
    }
    
    .overlay{
     position: absolute;
     display: none;
    
     top: 0px;
     left: 0px;
    
     height: 100%;
     width: 100%;
    
     background-color: rgba(0,0,0,0.5);
    }
    
    .overlay p {
     position: relative;
     text-align: center;
    
     color: #fff;
    }
    
    .tile:hover .overlay{
     display: block;
    }