2013-06-04 55 views
1

我需要爲〜20種顏色創建類,但是我需要爲每個顏色創建兩個 - 一個用於背景顏色,另一個用於邊界。我知道我可以這樣做每種顏色:減少 - 爲顏色生成背景和邊界類

@green: #00A300; 

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

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

但我認爲應該有更有效的方法。類似的東西,我指定變量,然後它循環所有顏色,並生成CSS模式:

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

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

這甚至可能嗎?

回答

4

這不是太難使用Selector interpolation一個mixin做:

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

    [email protected]{bg-name} { 
     background-color: @value; 
    } 
    [email protected]{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; 
} 
+0

我嘗試編譯您確切的代碼,但它表示,是第7行的語法錯誤 - '。@ {bg-name} {' –

+0

@PavelŠtěrba對於LESS 1.3.0,將選擇器包裝在'(〜「'和'」)'中,例如'(〜「。@ {bg-name}」)' – freejosh

+0

@freejosh謝謝!主要歸功於zzzzBov,它能夠滿足我的需求! –