CSS how to make an element fade in and then fade out?

后端 未结 5 581
没有蜡笔的小新
没有蜡笔的小新 2020-11-29 20:11

I can make an element with an opacity of zero fade in by changing its class to .elementToFadeInAndOut with the following css:

.elementToFadeInAndOut {
    op         


        
5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-29 20:49

    Use css @keyframes

    .elementToFadeInAndOut {
        opacity: 1;
        animation: fade 2s linear;
    }
    
    
    @keyframes fade {
      0%,100% { opacity: 0 }
      50% { opacity: 1 }
    }
    

    here is a DEMO

    .elementToFadeInAndOut {
        width:200px;
        height: 200px;
        background: red;
        -webkit-animation: fadeinout 4s linear forwards;
        animation: fadeinout 4s linear forwards;
    }
    
    @-webkit-keyframes fadeinout {
      0%,100% { opacity: 0; }
      50% { opacity: 1; }
    }
    
    @keyframes fadeinout {
      0%,100% { opacity: 0; }
      50% { opacity: 1; }
    }

    Reading: Using CSS animations

    You can clean the code by doing this:

    .elementToFadeInAndOut {
        width:200px;
        height: 200px;
        background: red;
        -webkit-animation: fadeinout 4s linear forwards;
        animation: fadeinout 4s linear forwards;
        opacity: 0;
    }
    
    @-webkit-keyframes fadeinout {
      50% { opacity: 1; }
    }
    
    @keyframes fadeinout {
      50% { opacity: 1; }
    }

提交回复
热议问题