2016-01-11 47 views
1

我需要下面的CSS輸出。 ie*類必須在那裏才具有特異性,body類也需要在那裏,因爲它們不會總是被添加。改進此規則的嵌套更少?

body.my-class, 
html.ie7 body.my-class, 
html.ie8 body.my-class, 
html.ie9 body.my-class { 
    background: red; 
} 

我可以在我的Less中得到同樣的結果。然而它不是一個好主意,因爲我必須兩次寫出background: red的風格。所以如果它被更新了,它需要在兩個地方更新。

body.my-class { 
    background: red; 
    html.ie7 &, 
    html.ie8 &, 
    html.ie9 { 
    background: red; 
    } 
} 

我可以用不同的方式寫我的Less,以便我不重複樣式,但是使編譯的CSS完全一樣嗎?

回答

4

只需在頂層嵌套內添加&(父選擇器)作爲逗號分隔的選擇器列表之一。較少的編譯器會自動使用完整的父選擇器替換它,因爲它總是如此。

body.my-class { 
    &, /* this will replaced with body.my-class as is always the case with parent selectors */ 
    html.ie7 &, 
    html.ie8 &, 
    html.ie9 &{ 
    background: red; 
    } 
} 

上面的代碼在編譯時會導致完全相同的CSS輸出。

body.my-class, 
html.ie7 body.my-class, 
html.ie8 body.my-class, 
html.ie9 body.my-class { 
    background: red; 
}