What is the most effective method to change color for multiple similar elements in LESS?

主宰稳场 提交于 2019-12-01 13:38:23

Use LESS mixins, lists and loops to generate a repetitive CSS code:

@product-colors:
    white  #fff,
    green  #0f0,
    yellow #ff0,
    black  #000,
    red    #f00;

.menu-template(@name, @color) {
    &.menu-@{name} {
        background-color: @color;
        color: darken(@color, 20%);
        &:hover {
             background-color: darken(@color, 10%);
        }
    }
}

.make-menus() {
    .-(length(@product-colors));
    .-(@i) when (@i > 0) {
        .-((@i - 1));
        @value: extract(@product-colors, @i);
        @name:  extract(@value, 1);
        @color: extract(@value, 2);
        .menu-template(@name, @color);
    }
}

li {
    .make-menus();
}

It is possible to use the .menu-template mixin directly without need for the @product-colors list and the corresponding loop. This actually results in a shorter and more readable code (until you need these colors to generate some other repetitive CSS classes):

li {
    .menu-template(white,  #fff);
    .menu-template(green,  #0f0);
    .menu-template(yellow, #ff0);
    .menu-template(black,  #000);
    .menu-template(red,    #f00);
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!