cssscalingcross-fade

CSS Scaling Image On Hover Combined With Timered Cross Fade


Here is how I scale an image on hover:

img {
    transition: 0.25s ease;
}
img:hover {
    transform: scale(0.75);
    transition: 0.25s ease;
}

Here is how I cross fade two images:

#cf {
  position:relative;
  margin:0 auto;
}

#cf img {
  position:absolute;
  left:0;
  -webkit-transition: opacity 1s ease-in-out;
  -moz-transition: opacity 1s ease-in-out;
  -o-transition: opacity 1s ease-in-out;
  transition: opacity 1s ease-in-out;
}

#cf img.top {
    -webkit-transition: opacity 1s ease-in-out;
    -webkit-animation: fade 5s infinite;
}

@-webkit-keyframes fade {
    0% {opacity: 0;}
    50% {opacity: 1;}
    100% {opacity: 0;}
}

https://jsfiddle.net/1n279ct8/

And here is what I get when I attempt to combine the two:

https://jsfiddle.net/h453xaav/

Ouch! It's treating only the "top" layer as hoverable.

This behaviour absolutely makes sense to me, but, frustratingly, I can't see the elegant workaround.

Is it possible in pure CSS, or is it time for me to break out the JavaScript?

Thank you in advance :-)

P.S. I've kept the code as simple as possible. In my actual work I use ids and classes and do cases for different browsers, but I cut a bit of that out here for the purposes of conveying as clearly as possible what I mean. This is my first post here, so I'm not sure the house style. Please let me know if I'm supposed to make it "complete" or just "proof of concept" to get the message across :-)

P.P.S. If the way I'm doing the CSS of these two effects is already incorrect or "dodgy" then please let me know!


Solution

  • You can't hover two instances at the same time, you can only hover a single element, and its parents (not its siblings).

    A work around is you can wrap both images within a div (think of this as a parent element). Then scale the contents of the div.

    The result can be seen in the fiddle below:

    #wrap:hover {
      transform: scale(0.75);
      -webkit-transform: scale(0.75);
      transition: 0.25s ease;
    }
    #wrap {
      position: relative;
      transition: 0.25s ease;
      background: red;
      /* remove this colour, this is just to help show the div shrinking*/
      width: 292px;
      /* this needs to be defined */
      height: 291px;
    }
    img.top {
      position: absolute;
      left: 0px;
      -webkit-transition: opacity 1s ease-in-out;
      -webkit-animation: fade 5s infinite;
      transition: 0.25s ease;
    }
    @-webkit-keyframes fade {
      0% {
        opacity: 0;
      }
      50% {
        opacity: 1;
      }
      100% {
        opacity: 0;
      }
    }
    <div id="wrap">
      <img class="bottom" src="http://i.imgur.com/qiupijw.png" />
      <img class="top" src="http://i.imgur.com/IAUlHar.png" />
    </div>