How can I call a mixin by reference in LESS?

a 夏天 提交于 2019-12-10 14:17:18

问题


The logical way would be:

.mymixin() {
  sample_key: samplevalue;
}

@avar:  mymixin;
.@{avar}();

but I get a parse error.

Is there a way to do it?


回答1:


Module mixins

If you want to call a specific mixin by a reference from a variable you would need to use a parameter, as you can not dynamicaly call parametric mixins by their names. So, the closest to what you want to do, would be using module mixins.

It would look like this in LESS:

.mixin(mymixin) {
  sample_key:samplevalue;
}

.mixin(anothermixin) {
  another_key:anothervalue;
}

@avar: mymixin;
.mixin(@avar);

the output CSS will be as expected:

sample_key: samplevalue;

and if you would change @avar to anothermixin you would specifically call the second mixin.

Here makes @ScottS a great use of this approach: LESS CSS Pass mixin as a parameter to another mixin

Edit:

To elaborate the answer a bit further. Why your approach wouldn't work? The problem is in selector/rule interpolation, where the line needs to have the following structure:

.prefix-satring-@{classname} some-more-string { property:value; }

so you can not call a mixin with it as it expects a { after the selector name and also an unescaped ( is not accepted as valid syntax in rule interpolation.

Additional info:

Similarly, you can not dynamically generate property names in LESS. So you can not do anything like .myclass{-webkit-@{property}:value;}, where this is possible in Sass (another very popular preprocessor language). However, there are some workarounds for that.

Another issue, that might be of notion here is that the interpolated classes (e.g. .@{avar}{something:something;}) get directly rendered into CSS and do not exist as LESS object/mixins, that you could reuse.



来源:https://stackoverflow.com/questions/16506146/how-can-i-call-a-mixin-by-reference-in-less

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!