CSS3 background image transition

前端 未结 13 2349
梦如初夏
梦如初夏 2020-11-22 07:07

I\'m trying to make a \"fade-in fade-out\" effect using the CSS transition. But I can\'t get this to work with the background image...

The CSS:



        
13条回答
  •  无人共我
    2020-11-22 07:53

    Considering background-images can't be animated, I created a little SCSS mixin allowing to transition between 2 different background-images using pseudo selectors before and after. They are at different z-index layers. The one that is ahead starts with opacity 0 and becomes visible with hover.

    You can use it the same approach for creating animations with linear-gradients too.

    scss

    @mixin bkg-img-transition( $bkg1, $bkg2, $transTime:0.5s ){  
      position: relative;  
      z-index: 100; 
      &:before, &:after {
        background-size: cover;  
        content: '';    
        display: block;
        height: 100%;
        position: absolute;
        top: 0; left: 0;    
        width: 100%;    
        transition: opacity $transTime;
      }
      &:before {    
        z-index: -101;
        background-image: url("#{$bkg1}");    
      }
      &:after {    
        z-index: -100;
        opacity: 0;
        background-image: url("#{$bkg2}");    
      }
      &:hover {
         &:after{
           opacity: 1; 
         }
      }  
    }
    

    Now you can simply use it with

    @include bkg-img-transition("https://picsum.photos/300/300/?random","https://picsum.photos/g/300/300");
    

    You can check it out here: https://jsfiddle.net/pablosgpacheco/01rmg0qL/

提交回复
热议问题