LESS中的多个选择器 [英] Multiple selectors in loop in LESS

查看:1911
本文介绍了LESS中的多个选择器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using the following code to generate a column layout using 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...

创建一个新的更少的函数,其将给出输出:

How would i now create a new less function that would give an output of:

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

其中 N 定义为 @columnCount:24; ,尽管列计数未设置,它可以更改为任何数字。我知道我可以为每个 grid_X 创建一个主体,以避免它保持杂乱。

Where N is defined as @columnCount: 24;, though the column count is not set, it can be changed to any number. I am aware i could create a body for each grid_X would like to avoid it to keep clutter down.

推荐答案

在LESS 1.4中使用:extend() +



它更优雅。你首先在硬编码的 .grid_1 类中定义要扩展的初始值(目前,LESS不会扩展动态生成的类),然后在你的循环扩展到该类。像这样:

Using :extend() in LESS 1.4+

This seems to accomplish it more elegantly. You first define the initial values you will want extended in a hard coded .grid_1 class (at present, LESS will not extend dynamically generated classes), then add an extender mixin in your loop to extend to that class. Like so:

.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;
}

这篇关于LESS中的多个选择器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆