Generate variables with loops (“Shorter/friendly-n

2020-02-07 04:51发布

问题:

I know that in LESS is possible to generate many CSS classes using loops. I personally used this technique to answer another user's question.

Now I'm facing the following code:

@transparent-black-10: fade(@nero, 0.1);
@transparent-black-20: fade(@nero, 0.2);
@transparent-black-30: fade(@nero, 0.3);
@transparent-black-40: fade(@nero, 0.4);
@transparent-black-50: fade(@nero, 0.5);
@transparent-black-60: fade(@nero, 0.6);
@transparent-black-70: fade(@nero, 0.7);
@transparent-black-80: fade(@nero, 0.8);
@transparent-black-90: fade(@nero, 0.9);

@transparent-white-10: fade(@bianco, 0.1);
@transparent-white-20: fade(@bianco, 0.2);
@transparent-white-30: fade(@bianco, 0.3);
@transparent-white-40: fade(@bianco, 0.4);
@transparent-white-50: fade(@bianco, 0.5);
@transparent-white-60: fade(@bianco, 0.6);
@transparent-white-70: fade(@bianco, 0.7);
@transparent-white-80: fade(@bianco, 0.8);
@transparent-white-90: fade(@bianco, 0.9);

I'm wondering if is possible to generate also LESS variables like above, using Loops, or this is denied by language. If possible, do you have some suggestion to generate above code more efficiently?

回答1:

(Now when Less v3.x and higher provides native support for custom functions).

Just as in most of other programming language, instead of a list of auto-generated/predefined variables, this programming problem is solved via function functionality. I.e. you define a function like:

.transparent-black(@value) {
    return: fade(@nero, @value ./ 10);
}

And then instead of @transparent-black-* variable you simply use .transparent-black(*)[] function call, e.g.:

div {
    color: .transparent-black(50)[];
}

This is obviously a simplified example (in a real project I certainly would make black/white/etc to be the function parameters too).



标签: loops less