【问题标题】:Improve Less nesting for this rule?改进这条规则的更少嵌套?
【发布时间】:2016-01-12 00:02:46
【问题描述】:

我需要以下 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 完全一样?

【问题讨论】:

    标签: less


    【解决方案1】:

    只需将&(父选择器)添加为顶级嵌套中的逗号分隔选择器列表之一。 Less 编译器会像往常一样自动将其替换为完整的父选择器。

    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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-11-08
      • 2018-06-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-13
      • 1970-01-01
      相关资源
      最近更新 更多