css - Less CSS - 访问部分类名并在 mixin 中使用

标签 css twitter-bootstrap sass less

在 Less 中,是否可以访问类名的一部分并在 mixin 中使用?

最好用一个例子来解释:

我有一个网格,我声明如下:

.columns (@columns) {
    //code here to generate column widths
}

//This is where my problem is:
.column-1 {
    .col (1)
}
.column-2 {
    .col (2)
}
.column-3 {
    .col (3)
}
// etc etc

显然这里有很多重复的代码。理想情况下,我希望能够不必声明 column-1 column-2 等,并且有一些方法,也许是正则表达式,解析类名,并使用破折号后的值自动计算列宽。我几乎可以肯定 twitter bootstrap 正在做类似的事情,但我无法理解:

.spanX (@index) when (@index > 0) {
      (~".span@{index}") { .span(@index); }
      .spanX(@index - 1);
    }
    .spanX (0) {}

最佳答案

我想你会明白的:

.columnX (@index) when (@index > 0) {          // Guarded mixin: use this mixin when the condition is true (like an if statement)
    (~".column-@{index}") {                    // outputs .column-0 as a class name
        .col(@index);                          // for the contents, use the col mixin
    }    // which class you are doing

    .columnX(@index - 1);                      // Recursive call to the same mixin, going down by 1
}
.columnX (0) {} // Default implementation so that when .columnX(0) is called, a matching mixin is found.

.col (@index) {
    // actual css that will be applied to column-1 if @index is 1
    width: @index * 10px; // for example
}
.columnX(3);                                   // number of columns you want

编辑(遗漏了 .columnX(3);; ) 编辑 添加了更多评论

所有这些应该给出结果:

.column-3 {
    width: 30px;
}
.column-2 {
    width: 20px;
}
.column-1 {
    width: 10px;
}

关于css - Less CSS - 访问部分类名并在 mixin 中使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11231366/

相关文章:

javascript - 一键刷新2个div Jquery

css - 如何居中图像和左右浮动文本?

php - 如何在 Assetic 中为 Compass 和 Yui CSS 使用过滤器?

css - 如何解决这个 sass 插值问题

html - 使用 CSS 设置图像的纵横比

html - 即使悬停状态消失也保持过渡

javascript - 嵌入受 CSS 影响的小部件

css - HTML5 CSS 样式问题

javascript - Angular JS 转发器 + Bootstrap 轮播

javascript - 使用复选框增加 Bootstrap 进度条