cssfadeincss-transitionscss-animations

Different CSS transition for *IN* and *OUT* (or returning from transitioned state)


I have a loading image which comes up during an Ajax load event. The image shows/hides by adding or removing a "loading" class to the body element. Currently, the loading image animates background-size from 0 to 100%, and fades in the opacity (vice versa for the 'return' transition).

I want to have the background-size transition happen instantly (not transition) on the fade out, so:

I've changed transition property for this selector .loading #loader .image to "opacity" rather than "all", but it still performs the background-size transition.

Does anyone know how to achieve the different fade in and fade out transitions described above with CSS?


Solution

  • Here is a simplified test case:

    div {
        background: blue;
        opacity: 0;
        transition: opacity 2s ease-in-out;
    }
    
    div.loading {
        opacity: 1;
        background: red;
        transition: opacity 2s ease-in-out, background 1s ease-in;
    }
    

    Notice how the opacity fades the same in and out, but the background only fades in, and immediately turns blue on fade out.

    I used :hover as an example, but it should work the same when adding and removing classes with JavaScript.

    Demo

    If you'd like a more specific example please provide a reduced test case on dabblet or Jsfiddle.