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

时间:2015-01-07 00:05:50

标签: css less

目前我正在使用下面的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 {
    ...
}

谢谢!

1 个答案:

答案 0 :(得分:4)

您可以使用extend()

  

Extend是一个Less伪类,它将放置的选择器与它引用的选择器合并。

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

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

由于基类正在扩展,因此不需要将其包含在循环中。该指数现在从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%;
}