Search code examples
csswebkitkeyframe

Shortening css3 animation keyframe definitions


While I was writing many quasi-identical CSS3 animations, I wondered if there's a way to shorten the code.
Each time, only the final keyframe is different.

@-webkit-keyframes one {
    from {
        [identical properties]
    }
    [...etc...]
    80% {
        [identical properties]
    }
    to {
        margin-left: 20px;
    }
}

@-webkit-keyframes two {
    from {
        [identical properties]
    }
    [...etc...]
    80% {
        [identical properties]
    }
    to {
        margin-left: 50px;
    }
}

That code is pretty long so I thought it could be easily shortened but looks like you have to define the whole animation over and over. I tried something like this, but that doesn't work in Chrome and Safari.

@-webkit-keyframes one, two {
    from {
        [identical properties]
    }
    [...etc...]
    80% {
        [identical properties]
    }
    to {
        margin-left: 20px;
    }
}

@-webkit-keyframes two {
    to {
        margin-left: 50px;
    }
}

Is there no way to define 2 identical animations? :o


Solution

  • To avoid copy-pasting during development, you can use a CSS preprocessor, such as SCSS / SASS and LESS. The mixin feature greatly reduces the code size:

    For a single property, writing a single mixin is sufficient:

    .Duplicates(@marginLeft) {
        from { /* ... */ }
        80%  { /* ... */ }
        to { margin-left: @marginLeft;}
    }
    @-webkit-keyframes one {
        .Duplicates(20px);
    }
    @-webkit-keyframes two {
        .Duplicates(50px);
    }
    

    Demo: An animated busy supermarket, using pure CSS(3)

    For me, the previous mixin was not sufficient. I also wanted dynamic names and vendor-prefixes how?, so that I do not have to write a rule 10 x 5 = 50 times (10 names, 5 vendors). That's a chance to show the power of a CSS preprocessor: