Reputation: 469
Basically, I want to be able to loop through break points creating, say centre-block-* classes.
Code:
.centre-block {
margin: 0 auto;
}
@breakpoints: xs 479px, sm 767px, md 991px, lg 1200px;
.make-classes(centre-block, @breakpoints);
.make-classes(@prefix, @list) {
.iter(length(@list));
.iter(@i) when (@i > 0) {
.iter(@i - 1);
@pair: extract(@list, @i);
@key: extract(@pair, 1);
@value: extract(@pair, 2);
@media (max-width: @value) {
.@{prefix}-@{key} {
.@{prefix};
}
}
}
}
From that, what I want to be able to do is add a class, say centre-block-sm
that, when the screen size is under 768px the .centre
classes margin: 0 auto
will be applied. But I want to be able to do this for numerous class types, like adding a no-padding-*
class list.
Everything works except for the fact it will not use the .@{prefix}
, and instead simply doesn't recognise it. If I replace .@{prefix}
with .centre-block
it works. Is there a way around this, perhaps a different approach to the problem?
I feel like this sort of functionality is what LESS was designed for, so I might just be missing the point altogether.
Upvotes: 1
Views: 57
Reputation: 89750
What you're trying to do is currently not possible with Less. You can find this discussed in this thread. Though there is not much explanation in this, you can see that other linked thread within this (#1133) which mentions that this functionality is not yet implemented.
You could have a look at using detached rulesets as an alternative. In your code, convert the top level class selector (.centre-block
) into a detached ruleset, store it as a variable and then pass it as one parameter to the mixin. We can then invoke this ruleset within the mixin call and it will print the content of the ruleset as it is into whichever selector we need. Below is a sample:
@centre-block : {margin: 0 auto;}; /* a detached ruleset */
@breakpoints: xs 479px, sm 767px, md 991px, lg 1200px;
.make-classes(centre-block, @breakpoints, @centre-block); /* pass the extra param */
.make-classes(@prefix, @list, @ruleset) { /* add the extra param */
.iter(length(@list));
.iter(@i) when (@i > 0) {
.iter(@i - 1);
@pair: extract(@list, @i);
@key: extract(@pair, 1);
@value: extract(@pair, 2);
@media (max-width: @value) {
.@{prefix}-@{key} {
@ruleset(); /* invoke the ruleset */
}
}
}
}
Upvotes: 2