Luca Detomi Luca Detomi - 11 months ago 156
Less Question

LESS: Combine multiple CSS3 animation

I have 2 CSS animations defined in LESS:

.color_animation (@color, @time:1s)
{
@stop-1:~"@{color}_SOPRA";
@stop-2:~"@{color}_SOTTO";

@name: ~"[email protected]{color}";
animation:@name @time ease-in-out infinite alternate;

.steps()
{
0% { color:@@stop-1; }
50% { color:@@stop-2; }
100% { color:@@stop-1; }
}

@keyframes @name { .steps(); }
}


.zoom_animation (@ratio, @time:1s)
{
@zoom-ratio:round(@ratio*100);
@name: ~"[email protected]{zoom-ratio}";

animation:@name @time ease-in-out infinite alternate;

.steps()
{
0% { .scale(1.0); }
50% { .scale(@ratio); }
100% { .scale(1.0); }
}

@keyframes @name { .steps(); }
}


each one is called by a different CSS class:

.blink
{
.color_animation(red);
}

.animated-zoom
{
.zoom_animation(1.05);
}


I would like to be able to execute one of them or both in the same time, adding one or both css classes to a DOM element, for example:

<p class='blink'>Loading...</p>
<p class='animated-zoom'>Highlight</p>
<p class='blink animated-zoom'>Data not Saved!!!</p>


But in last case, second animation overrides the first one.

How to combine them in the special case in which both classes are added?

Answer Source

Thanks to @seven-phases-max's suggestion, I elaborated a possible solution, pipelining animations in case more than one CSS class is assigned to an element.

Here my original (now slightly modified) code, in which I move common parts in dedicated COMMONS mixins:

.color_animation (@color, @time:1s)
{
  @stop-1:~"@{color}_SOPRA";
  @stop-2:~"@{color}_SOTTO";

  @name: ~"[email protected]{color}";

  .steps()
  {
      0% { color:@@stop-1; }
    100% { color:@@stop-2; }
  }

  @value:@name @time ease-in-out infinite alternate;

  .INITIALIZE_keyframes();
  .CALL_animation();
}


.zoom_animation (@ratio, @time:1s)
{  
  @zoom-ratio:round(@ratio*100);
  @name: ~"[email protected]{zoom-ratio}";

  .steps()
  {
      0% { .scale(1.0); }
    100% { .scale(@ratio); }
  }

  @value:@name @time ease-in-out infinite alternate;

  .INITIALIZE_keyframes();
  .CALL_animation();
}

Here the COMMONS mixins declaration (I'm missing browsers browsers prefix for simplicity, but they could be added here):

.INITIALIZE_keyframes()
{
  @keyframes @name { .steps(); }
}

.CALL_animation()
{
  animation+:@value;
}

Please, note the '+' sign in animation declaration, it's the secret of my solution, coupled with the following CSS classes declaration:

.blink
{
  .color_animation(red);
}

.animated-zoom
{
  .zoom_animation(1.05);
}

.blink
{
  &.animated-zoom
  {  
    .color_animation(red);
    .animated-zoom;
  }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download