Amino Amino - 3 months ago 16
Less Question

How have dynamic class names in LESS CSS and use them as values in function

I want generate flexible color classes for another class like this without writing all of them on LESS as variables:

.link.color-green{
color:green;
}
.link.color-red{
color:red;
}

.link.color-cccccc{
color:#cccccc;
}

.link.color-FFF8DC{
color:#FFF8DC;
}


maybe something like this? but compiler say error:

NameError: variable @colorNameOrHexaCode is undefined

.link{
.color-@{colorNameOrHexaCode} {

color: rgb(@colorNameOrHexaCode);

};
}


I'm not sure how make loop or function for this, sorry.

Answer

You have to create a list of colors first before creating a loop:

.make-classes(@prefix, @list) {
    .iter(length(@list));
    .iter(@i) when (@i > 0) {
        .iter(@i - 1);
        @pair:  extract(@list, @i); 
        @key: extract(@pair, 1);
        @value: extract(@pair, 2); 
        .@{prefix}.color-@{key} {
            color: @value;  
        }
    }
}

@colors:
    ~'blue' #7FB3D4,
    ~'gray' #767676,
    ~'green' #8CC079,
    ~'red' #b35d5d;

.make-classes(link, @colors);

Output:

.link.color-blue {
  color: #7fb3d4;
}
.link.color-gray {
  color: #767676;
}
.link.color-green {
  color: #8cc079;
}
.link.color-red {
  color: #b35d5d;
}
Comments