How should I reset a less variable using its own v

2019-08-06 04:49发布

I want to create a rgba from a color less variable and assign the result to the same variable, but I can't do this by the following code.

@navbar-default-bg: rgba(red(@navbar-default-bg), green(@navbar-default-bg), blue(@navbar-default-bg), 0.9);

标签: less
1条回答
贼婆χ
2楼-- · 2019-08-06 05:11

The above code would result in the following error being thrown on compilation:

NameError: Recursive variable definition for @navbar-default-bg

Recursive variable definitions won't work in Less because of the way Less does lazy loading of the variables. This would mean that the last definition for that variable (within the same scope) will be the one that is used. In your example it would result in an error because the variable cannot reference itself (to get its originally declared value).

Quoting Less Website:

When defining a variable twice, the last definition of the variable is used, searching from the current scope upwards. This is similar to css itself where the last property inside a definition is used to determine the value.


The best way to create a rgba color value from a given rgb color is to use the built-in fade function (like shown below). But note that, the value cannot be assigned back to the same variable.

@navbar-default-bg: rgb(255, 0, 0);

#sample{
    color: fade(@navbar-default-bg, 90%);
}

The above Less code when compiled would produce the following CSS output:

#sample {
    color: rgba(255, 0, 0, 0.9);
}

Of-course, you could do something like mentioned in this answer to sort of achieve a reset effect but my personal opinion is that it is way too much complexity and effort for something that can probably be achieved in a different way.

Here is a sample implementation of the method mentioned in that answer adapted to suit this question. (Code is added below just in-case the link becomes inactive.)

.init() {
    .inc-impl(rgb(255, 0, 0), 0.1); // set initial value
}
.init();
 .inc-impl(@new, @i) {
    .redefine() {
        @color: @new;
        @alpha: @i;
    }
}
.someSelector(@name) {
    .redefine(); // this sets the value of counter for this call only
    .inc-impl(rgba(red(@color), green(@color), blue(@color), @alpha), (@alpha + 0.1)); // this sets the value of counter for the next call 
    @className: ~"@{name}";
    .@{className}
    {
        color: @color;
    }
}
.someSelector("nameOfClass");
.someSelector("nameOfClass1");
.someSelector("nameOfClass2");
查看更多
登录 后发表回答