使用 Less 循环创建逗号分隔的选择器

Create comma separated selectors with Less loop

目前我正在使用下面的 Less 代码为我的网格元素创建默认值:

.create-grid-elements(@n, @i: 1) when (@i =< @n) {
    .grid_@{i} {
        position: relative;
        display:inline;
        float: left;
        margin-left: 1%;
        margin-right: 1%;
    }
    .create-grid-elements(@n, @i+1);
}

.create-grid-elements(16);

输出:

.grid_1 {
    ...
}

.grid_2 {
    ...
}

...

.grid_16 {
    ...
}

为了使用浏览器开发工具进行调试,有没有一种方法可以调整循环(或编写一个新循环),而不是为网格编写多个独立的选择器,而是编写一个逗号选择器就这样分开了?

.grid_1, .grid_2, ... , .grid_16 {
    ...
}

谢谢!!

您可以使用 extend():

Extend is a Less pseudo-class which merges the selector it is put on with ones that match what it references.

只需创建一个基础 class,在本例中为 .grid_1

然后 extend 它在循环内:.grid_@{i}:extend(.grid_1) {}.

由于基础 class 正在扩展,因此不需要将其包含在循环中。索引现在从 2 开始。

.grid_1 {
    position: relative;
    display:inline;
    float: left;
    margin-left: 1%;
    margin-right: 1%;
}

.create-grid-elements(@n, @i: 2) when (@i =< @n) {
    .grid_@{i}:extend(.grid_1) {}
    .create-grid-elements(@n, @i+1);
}

.create-grid-elements(16);

输出:

.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 {
    position: relative;
    display: inline;
    float: left;
    margin-left: 1%;
    margin-right: 1%;
}