2

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

Andy
  • 49,085
  • 60
  • 166
  • 233
Daan
  • 1,879
  • 17
  • 18

3 Answers3

1

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:

Community
  • 1
  • 1
Rob W
  • 341,306
  • 83
  • 791
  • 678
1

Not at the moment. Remember that if you are gzipping your CSS that a lot of this inefficiency will disappear.

Rich Bradshaw
  • 71,795
  • 44
  • 182
  • 241
1

Not inherently. Especially with vendor prefixes, CSS can get really dizzying, however if you are deploying the file properly (GZip, caching, etc.) it's not really an inefficiency, just a pain in the butt to write.

Depending on your project, you can parse CSS as PHP and define variables there. I find the idea really sexy but haven't had enough of a need to use it.

Isaac Lubow
  • 3,557
  • 5
  • 37
  • 53