Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic Variable Names in LESS CSS

Tags:

I have been trying this for a while, looking at other answers, but to no avail. Hopefully someone can help me.

I am trying to generate some dynamic variable names within a mixin.

The variables are already defined:

@horizontal-default-color: #fff; @horizontal-inverse-color: #000; 

etc..

The mixin I want would be something like this:

.horizontal-variant(@variant) {     color: @{horizontal-@{@variant}-color} } 

And the result I am expecting, when called:

.horizontal-default{    .horizontal-variant(~"default"); } .horizontal-inverse{    .horizontal-variant(~"inverse"); } 

is

.horizontal-default {color: #fff} .horizontal-inverse {color: #000} 

Unfortunately I run into errors every time.

I know this can be done, I have seen it being used in Font Awesome LESS where @{fa-css-prefix} is defined in variables. I am just having trouble transporting the same solution in my project.

You can try testing the code at http://lesstester.com/

like image 633
elvista Avatar asked May 23 '14 07:05

elvista


People also ask

Can you use CSS variables in less?

As we know, less function can't work with css variables.

Can SCSS variable change dynamically?

We can dynamically update SCSS variables using ReactJS with the help of a project by achieving theme switching of the card component between light and dark theme.

Why variables should not be named dynamically?

Summary: Dynamically accessing variable names can negatively impact the readability of your code and can cause it to run slower by preventing MATLAB from optimizing it as well as it could if you used alternate techniques. The most common alternative is to use simple and efficient indexing.


1 Answers

You can use Variable Names. And I've tested the code at http://lesstester.com/, it works.

@horizontal-default-color: #fff; @horizontal-inverse-color: #000;  .horizontal-variant(@variant) {   @color: "horizontal-@{variant}-color";   color: @@color; }  .horizontal-default{   .horizontal-variant(default); } .horizontal-inverse{   .horizontal-variant(inverse); } 
like image 145
Miaonster Avatar answered Oct 21 '22 20:10

Miaonster