2016-01-11 51 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; 
}