Pavel Štěrba
Pavel Štěrba

Reputation: 2912

LESS - generate background and border classes for colors

I need to create classes for ~20 colors, but for each one i need to create two - one for background-color and second one for border. I know I can do it like this for every single color:

@green: #00A300;

.green-background {
    background-color: @green;
}

.green-border {
    border: 1px solid @green;
}

But I think there should be more effective way. Something like that I specify variables and then it loop all colors and generate CSS into pattern:

.[color]-background {
    background-color: [@color];
}

.[color]-border {
    border: 1px solid [@color];
}

Is this even possible?

Upvotes: 1

Views: 410

Answers (1)

zzzzBov
zzzzBov

Reputation: 179046

This isn't too hard to do with a mixin using Selector interpolation:

LESS:
.color(@name, @value) {
    //selector interpolation works when the entire
    //variable is used as the selector
    @bg-name: ~"@{name}-background";
    @border-name: ~"@{name}-border";

    .@{bg-name} {
        background-color: @value;
    }
    .@{border-name} {
        border: 1px solid @value;
    }
}
//be sure to quote the first parameter in case your color name gets
//interpreted as a value, blue would pass #00F which you don't want
.color('blue', #0000FF);
CSS:
.blue-background {
  background-color: #0000ff;
}
.blue-border {
  border: 1px solid #0000ff;
}

Upvotes: 4

Related Questions