LESS / CSS:避免很多LOC?

时间:2015-08-19 19:16:01

标签: css less loc

我想知道我是否可以改进我的LESS-Snippet。我有很多变量与colornames /我自己的颜色标题和相关的前景和背景颜色。我在我的颜色之后定义了类名。

@logocolorgreen: #40FF01;      @logocolorgreenname: green;             @logocolorgreenitem: #404040;
@logocolormidblue: #01C0FF;    @logocolormidbluename: midblue;         @logocolormidblueitem: #404040;
@logocolorpurple: #C00031;     @logocolorpurplename: purple;           @logocolorpurpleitem: white;
@logocoloryellow: #FFC000;     @logocoloryellowname: yellow;           @logocoloryellowitem: #404040;
    // ... more Colors


div { 
    .mixedin(@colorname) {
        @bgvarname: "logocolor@{colorname}";
        background-color: @@bgvarname;
        @fgvarname: "logocolor@{colorname}item";
        color: @@fgvarname;
    }

    &.@{logocolorgreenname} {
        .mixedin(@logocolorgreenname); 
    }
    &.@{logocolormidbluename} {
        .mixedin(@logocolormidbluename); 
    }
    &.@{logocolorpurplename} {
        .mixedin(@logocolorpurplename); 
    }
    &.@{logocoloryellowname} {
        .mixedin(@logocoloryellowname); 
    }
    // ... more Colors
}

编译到

div.green {
  background-color: #40ff01;
  color: #404040;
}
div.midblue {
  background-color: #01c0ff;
  color: #404040;
}
div.purple {
  background-color: #c00031;
  color: white;
}
div.yellow {
  background-color: #ffc000;
  color: #404040;
}

我想知道,如果我能

  1. 避免过度重复使用Mixedin?
  2. 在每次混合使用中避免使用class cc和mixedin-parameter的双c& p?
  3. 谢谢!

1 个答案:

答案 0 :(得分:0)

您可以使用listsloops

//define the logo colours as a triplet of class name, background and foreground colors
@logocolorgreen: "green", #40FF01, #404040;
@logocolormidblue: "midblue", #01C0FF, #404040;
@logocolorpurple: "purple", #C00031, white;
@logocoloryellow: "yellow", #FFC000, #404040;

//pack the triplets into a list of all triplets to be used
@colors: @logocolorgreen, @logocolormidblue, @logocolorpurple, @logocoloryellow;

//this is how loops are made in less: recursion with default parameters and guards
//the  +1 on the length is necessary because lists in LESS are 1-indexed
.logocolors(@i: 1) when (@i < length(@colors) + 1) {
  .logocolors(@i + 1);

  @current: extract(@colors, @i); //current holds the triplet
  //explode the triplet into variables
  @current-name: e(extract(@current, 1)); //the e function converts a string to a selector
  @current-bg: extract(@current, 2);
  @current-fg: extract(@current, 3);

  //rule body
  &.@{current-name} {
    background-color: @current-bg;
    color: @current-fg;
  }
}
div {
  .logocolors();
}

此示例导致以下CSS输出:

div.yellow {
  background-color: #ffc000;
  color: #404040;
}
div.purple {
  background-color: #c00031;
  color: #ffffff;
}
div.midblue {
  background-color: #01c0ff;
  color: #404040;
}
div.green {
  background-color: #40ff01;
  color: #404040;
}

e()函数对于类名是必需的,因为如果你使用它们的原始值,LESS会将名称转换为#-colors,从而破坏输出语法。

正如评论中所建议的那样,您应该尽可能通过使用而不是内容来命名类名来重新考虑您的类名。