LESS中的多个选择器循环

时间:2013-08-09 18:53:34

标签: css less

我使用以下代码使用LESS CSS生成列布局:

.columnBuilder (@index) when (@index =< @columnCount) {

  .container_@{columnCount} .grid_@{index}  {
    width: unit(((@baseWidth / @columnCount) * @index)-10, px);
  }

  .columnBuilder(@index + 1);
}

这给了我一个输出:

.container_24 .grid_1 {
  width: 69px;
}
.container_24 .grid_2 {
  width: 148px;
}
.container_24 .grid_3 {
  width: 227px;
}

etc...

我现在如何创建一个新的less函数,它将输出:

.grid_1,
.grid_2,
....,
.grid_N {
  display: inline;
  float: left;
  margin-left: 5px;
  margin-right: 5px;
}

N定义为@columnCount: 24;,但未设置列数,可将其更改为任意数字。我知道我可以为每个grid_X创建一个机构,以避免它变得杂乱无章。

2 个答案:

答案 0 :(得分:5)

在LESS 1.4 +

中使用:extend()

这似乎更优雅地完成了它。首先定义要在硬编码的.grid_1类中扩展的初始值(目前,LESS不会扩展动态生成的类),然后在循环中添加扩展程序mixin以扩展到该类。像这样:

.grid_1 { //this acts as the "launch point" for extending them all
    display: inline;
    float: left;
    margin-left: 5px;
    margin-right: 5px;
}

.columnBuilder (@index) when (@index =< @columnCount) {
  //we are going to use this class twice, so just calculate it once
  @gridClass: ~'.grid_@{index}';
  //this is your original code except the variable now used for the grid class
  .container_@{columnCount} @{gridClass} {
    width: unit(((@baseWidth / @columnCount) * @index)-10, px);
  }
  //this is your extender feature, which does not do so for the initial .grid_1
  //which was set above as our launch point.
  @{gridClass} {
    .extender() when (@index > 1) {
      &:extend(.grid_1 all);
    }
    .extender() when (@index = 1) {}
    .extender();
  }
  //iterate the loop just as you were doing
  .columnBuilder(@index + 1);
}
//call the loop starting at 1
.columnBuilder(1);

输出是您的期望:

.grid_1,
.grid_2,
....,
.grid_N {
  display: inline;
  float: left;
  margin-left: 5px;
  margin-right: 5px;
}

答案 1 :(得分:0)

事实证明,LESS没有像这样的东西的原生支持,并且总是会创建多个CSS块,每个块都有自己的主体,所以你需要运行一些带有mixins的hack。我使用了以下内容:

.columnBuilderX (@index) when (@index = 1) {

  @isel: ~".grid_@{index}, ";

  .columnBuilderX (@index + 1, @isel);
}

.columnBuilderX (@index, @innerSel) when (@index =< (@columnCount - 1)) {

  @isel: @innerSel + ~".grid_@{index}, ";

  .columnBuilderX (@index + 1, @isel);
}

.columnBuilderX (@index, @innerSel) when (@index = @columnCount) {
  @isel: @innerSel + ~".grid_@{index} ";

  @{isel} {
    display: inline;
    float: left;
    margin-left: 5px;
    margin-right: 5px;
  }

  .columnBuilderX (@index + 1, @isel);
}

为我制作的:

.grid_1,  .grid_2,  .grid_3,  .grid_4,  .grid_5,  .grid_6,  .grid_7,  .grid_8,  .grid_9,  .grid_10,  .grid_11,  .grid_12,  .grid_13,  .grid_14,  .grid_15,  .grid_16,  .grid_17,  .grid_18,  .grid_19,  .grid_20,  .grid_21,  .grid_22,  .grid_23,  .grid_24 {
  display: inline;
  float: left;
  margin-left: 5px;
  margin-right: 5px;
}

第一个mixin是调用的初始mixin,它没有内部选择器,第二个mixin需要第二个param,这是我们在第一个中创建的变量,然后递归运行直到我们到达最后一列由when子句定义,我们添加最后一个没有逗号的选择器,然后使用我们内置的选择器列表来应用我们的CSS。

如果有人能提出比这更简单的事情,请创建一个答案。