改进此规则的较少嵌套?

时间:2016-01-11 15:55:36

标签: less

我需要以下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的样式。因此,如果它已更新,则需要在2个位置进行更新。

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

我可以用不同的方式编写我的Less,这样我就不会重复这个样式,但是编译后的CSS完全相同吗?

1 个答案:

答案 0 :(得分: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;
}