3

我正在使用以下代码使用 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想要避免它的人创建一个身体以保持混乱。

4

2 回答 2

5

:extend()在 LESS 1.4+ 中使用

这似乎更优雅地完成了它。您首先定义您希望在硬编码.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;
}
于 2013-08-10T05:05:08.497 回答
0

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

.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 需要第二个参数,这是我们在第一个中创建的变量,然后递归运行,直到我们点击定义的最后一列子句,我们在when其中添加最后一个不带逗号的选择器,然后使用我们内置的选择器列表来应用我们的 CSS。

如果有人能想出比这更简单的东西,请创建一个答案。

于 2013-08-09T20:58:18.610 回答