我尝试在其内部使用相同的.formater()
规则集。
我收到语法错误。
为什么我们不能在其内部使用规则集?
.formater(@className;@rules){
.@{className}{
@rules();
}
}
.formater(mainContainer;{
display:block;
line-height:2em;
& a{
colour: blue;
&.formater(link;{
colour:red;
});
}
});
如有任何帮助,我们将不胜感激。
最佳答案
语法错误的原因是您将 &
附加到不允许的 mixin 调用中。 &
只能附加到选择器。如果您在 mixin 调用之前删除 &
,那么您的代码将可以正常编译。
.formater(@className; @rules){
.@{className}{
@rules();
}
}
.formater(mainContainer; {
display:block;
line-height:2em;
& a{
colour: blue;
.formater(link; {
colour:red;
});
}
});
上面的 Less 代码编译后会生成以下 CSS:
.mainContainer {
display: block;
line-height: 2em;
}
.mainContainer a {
colour: blue;
}
.mainContainer a .link {
colour: red;
}
正如您所注意到的,上面输出的最终选择器是 .mainContainer a .link
而不是 .mainContainer a.link
。如果您试图实现后者,那么一种选择是在 .formater
mixin 代码本身中添加 &
。
.formater(@className; @rules) {
&.@{className} {
@rules();
}
}
我真的不建议使用下面的选项,但如果您需要 .formater()
mixin 来支持这两种变体,那么您可以使用变量和保护条件并酌情使用。
.formater(@className; @rules; @parent-append: false) {
& when not (@parent-append = false) {
&.@{className} {
@rules();
}
}
& when (@parent-append = false) {
.@{className} {
@rules();
}
}
}
然后您可以将 mixin 称为
.formater(link; {colour:red;}; true); /* if & should be appended */
或
.formater(link; {colour:red;};); /* if & need not be appended */
关于less - 为什么我们不能在同一个规则集中使用规则集?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33773872/