How to transition z-index?

前端 未结 3 1560
花落未央
花落未央 2021-01-17 10:48

https://jsfiddle.net/vaf6nv36/1/

Can the balloons image slowly transition over the apple image?

I think that I need more transition parameters, or I should use

3条回答
  •  不知归路
    2021-01-17 11:14

    Although theoretically you can transition z-index, it wouldn't make much sense, i.e. would not result in the crossfade effect which you obviously are looking for: z-index values are integers, which - when you change them in the smallest possible steps (integers, no commas) - results in states either before the other one OR behind the other one - no transitional "half states" in between. If you want to do a kind of continuous crossfade between two elements, you should use a transition on opacity.

    In your particular case, since your DIVs are not directly above each other, but only overlap each other, you can solve that by having a second DIV identical to img2 (I called its class .img3), but with z-index: 0 and this CSS rule:

    .img1:hover + .img2 {
      opacity: 0;
    }
    

    This will fade out img2, but still show img3, which however is behind img1, creating the impression of a transition between img1 and img2.

    https://jsfiddle.net/2a2epLfv/1/

    .img1,
    .img2,
    .img3 {
      border: 1px solid black;
      transition: 1s;
      position: absolute;
    }
    
    .img1 {
      left: 20%;
      height: 300px;
      width: 300px;
      z-index: 1;
      background-image: url(http://cdn.pcwallart.com/images/balloons-photography-vintage-wallpaper-1.jpg);
    }
    
    .img2,
    .img3 {
      right: 20%;
      width: 300px;
      height: 300px;
      top: 100px;
      background-image: url(https://i.pinimg.com/736x/c1/7b/15/c17b150e93c4e9c50d963b076484bee7--apple-wallpaper-iphone-wallpaper.jpg);
    }
    
    .img2 {
      z-index: 2;
    }
    
    .img3 {
      z-index: 0;
    }
    
    .img1:hover+.img2 {
      opacity: 0;
    }

提交回复
热议问题