Variable increment in LESS css

How can I increment a variable in LESS css?

Here is an example.

@counter: 1; .someSelector("nameOfClass", @counter); @counter: @counter + 1; .someSelector("nameOfClass", @counter); 

The above code snippet will cause this "syntax error"

 SyntaxError: Recursive variable definition for @counter 

Is there any work for this error? For example, is there an entry like @counter ++?

Thanks..

+7
css less
source share
1 answer

Impossible

See the documentation for LESS variables . Essentially, LESS variables are constants in the scope of their creation. They are lazy loaded and cannot be "changed" in this way. The most recent definition will be the one used by everyone in this area. In your case, an error will occur, since the variables cannot refer to them.

Consider the following example:

 @counter: 1; .someSelector("nameOfClass", @counter); @counter: 2; .someSelector("nameOfClass1", @counter); .someSelector(@name; @count) { @className: ~"@{name}"; .@ {className} { test: @count; } } 

The output will be 2 for both:

 .nameOfClass { test: 2; } .nameOfClass1 { test: 2; } 

This is because LESS defines @counter with the last variable definition in this area. It does not pay attention to the order of calls using @counter , but rather acts just like CSS, and takes into account the "cascade" of the variable.

For further discussion of this in LESS, you can track the discussion that occurs on this request to the LESS function .

The solution is in a recursive call set for a local variable

The seven-max phases are related to what, in his opinion, is a mistake in LESS, but I don't think so. Rather, it seems to me that this is a creative use of a recursive counter reset to get the desired effect. This allows you to achieve what you want (using my sample code):

 // counter .init() { .inc-impl(1); // set initial value } .init(); .inc-impl(@new) { .redefine() { @counter: @new; } } .someSelector(@name) { .redefine(); // this sets the value of counter for this call only .inc-impl((@counter + 1)); // this sets the value of counter for the next call @className: ~"@{name}"; .@ {className} { test: @counter; } } .someSelector("nameOfClass"); .someSelector("nameOfClass1"); 

Here is the CSS output:

 .nameOfClass { test: 1; } .nameOfClass1 { test: 2; } 

NOTE. . I believe that you are not changing a strict global value here, but setting a new local value each time .someSelector call .someSelector . Whether this is based on erroneous behavior or not is doubtful, but if so, this decision may disappear in the future. For further comments on the limitations of this method, see the discussion here .

+9
source share

All Articles