less - 为什么我们不能在同一个规则集中使用规则集?

标签 less less-mixins

我尝试在其内部使用相同的.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/

相关文章:

css - 少样式表语言 : prevent parentheses from being omitted in compiled CSS

less - 如何为 :hover, : active, :disabled? 等状态编写更少的 mixin

css - 如何忽略mixin中的传递参数

less - 如何重用其选择器是通过串联形成的 mixin

html - 用于大屏幕标题的 Bootstrap 3 网格列

html - 不可移植的 CSS : button background images do not display in some mobile browsers

css - 使用 mixins 时 Bootstrap 2 列问题

less - 合并较少 mixin 输出

windows - 在 Windows 上使用 node.js 在 PHPStorm 6 中设置一个 LESS 文件观察器?

php - 在 Windows 上使用 less 和 symfony2