Helpex - Trao đổi & giúp đỡ Đăng nhập

I am looking to do a for loop inside of Less. Is it possible to do this inside of Less? I know it has the capability to evaluate js but to this degree?

11 hữu ích 3 bình luận 8.3k xem chia sẻ

I will recommend to checkout Twitter Bootsrap. They are building their grid system that way. They loop, with recursion, in a less mixin, instead of typing every class they need.

The interesting part is in mixins.less file, in the less directory, below "// The Grid" comment (line 516). The interesting portion is:

#grid {

    .core (@gridColumnWidth, @gridGutterWidth) {

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


      .span (@columns) {
        width: (@gridColumnWidth * @columns) + (@gridGutterWidth * (@columns - 1));

Which is called in grid.less file in less directory this way:

#grid > .core(@gridColumnWidth, @gridGutterWidth);

Which produce (among other things):

.span12 {
  width: 940px;
.span11 {
  width: 860px;
.span10 {
  width: 780px;

in bootstrap.css line 170.

For @gridColumnWidth, @gridGutterWidth and the rest of variables check variables.less file (line 184)

Be sure to have the last version of lessc node compiler installed.

23 hữu ích 5 bình luận chia sẻ

There's nothing about loops in the docs, but since you can access JavaScript expressions via backticks, you could always define a function in your script (not your LESS code, but JavaScript — e.g., if in a browser, you'd have a separate script element) that does your loop and then access it, e.g.:

@height: `doMyLoop()`

It depends on what you're trying to achieve with the loop. If you want the loop to output CSS rules, I suspect you're out of luck.

2 hữu ích 2 bình luận chia sẻ

This is a hack but... Add this to your less file.

@testColor: green;

unusedclass {
    unknownprop: ~`loopCss(10,".group{{i}} { background-color: @{testColor}; }")`

Create a javascript file loopCss.js with the following function:

function loopCss(count,cssTemplate) {
    // end the existing unused class
    var result = "0;}\n";
    // Add your custom css
    for(var i=0; i<count; i++) result += cssTemplate.replace("{{i}}",i) +"\n";
    // Handle the close bracket from unused class
    result += "unusedclass {";
    return result;

Now include the loopCss.js before your less.js and it should work.

1 hữu ích 0 bình luận chia sẻ
Không tìm thấy câu trả lời bạn tìm kiếm? Duyệt qua các câu hỏi được gắn thẻ javascript css for-loop less , hoặc hỏi câu hỏi của bạn.

Có thể bạn quan tâm