Handling Multiple CSS3 Transitions with a LESS Mixin

Suppose you’d like to use a handy LESS mixin to handle multiple CSS3 transitions in a single statement. That’s what LESS is for! But this is a bit of a hairy task. It takes a little finagling. But it’s doable! Here’s how.

To set up multiple CSS3 transitions, you’d do something like this:

a.btn {
    background-color: blue;
    color: white;
    -webkit-transition: background-color, color .2s ease-in-out;
    -moz-transition:  background-color, color .2s ease-in-out;
    -ms-transition:  background-color, color .2s ease-in-out;
    -o-transition:  background-color, color .2s ease-in-out;
    transition:  background-color, color .2s ease-in-out;
}

It would be nice to do that in shorter form, using a LESS mixin. But by default LESS’s parametric mixins don’t like handling an indeterminate number of arguments. It can handle it (using ‘…’), but our case is even more complex, since we want to list multiple properties (separated by commas) followed by duration and easing (stated once for all).

There is a solution. Worked out and posted by Tony Stuck (and commenter Vicente) here, and presented in shorter form in stackoverflow, it works like this:

Set up your mixin with a bit of regular expression magic:

.transition (@value1,@value2:X,...)
{
    @value: ~`"@{arguments}".replace(/[[]]|,sX/g, '')`;

    -webkit-transition: @value;
    -moz-transition: @value;
    -ms-transition: @value;
    -o-transition: @value;
    transition: @value;
}

Then apply the mixin like this:

a.btn {
    background-color: blue;
    color: white;
    .transition(background-color, color .2s ease-in-out);
}

Nice.

Grateful.

Leave a comment