【问题标题】:Have 2 classes as parent selectors at different levels in Less?在 Less 中有 2 个类作为不同级别的父选择器吗?
【发布时间】:2016-01-12 13:28:42
【问题描述】:

我需要这个 CSS:

.class-1.class-a .target {
  background: red;
}

.class-1.class-b .target {
  background: blue;
}

我用这个 Less 可以很好地工作

.target {

  .class-1.class-a & {
    background: red;
  }

  .class-1.class-b & {
    background: blue;
  }
}

但是,我的 LESS 可以写得更简洁吗?写两次class-1似乎很可惜。我试过这个:

.target {

  .class-1 & {
    &.class-a {
      background: red;
    }

    &.class-b {
      background: blue;
    }
  }
}

还有这个:

.target {

  .class-1 & {
    .class-a & {
      background: red;
    }

    .class-b & {
      background: blue;
    }
  }
}

【问题讨论】:

    标签: less


    【解决方案1】:

    您的最后一次尝试非常接近,如果您将其修改为:

    .target {
      .class-1 & {
        .class-a& {
          background: red;
        }
        .class-b& {
          background: blue;
        }
      }
    }
    

    它会起作用的。

    请注意,同一级别的类的顺序无关紧要,因此生成的.class-a.class-1 .target 等于所需的.class-1.class-a .target

    (虽然我没有提到不惜一切代价避免重复的想法通常是有缺陷的。如果与您的初始代码甚至纯 CSS 本身相比,所有这些神秘的 & 和括号链使代码完全不可读)。

    【讨论】:

      猜你喜欢
      • 2016-02-23
      • 2016-08-22
      • 1970-01-01
      • 1970-01-01
      • 2016-01-02
      • 2013-10-22
      • 2014-01-10
      • 2017-06-04
      • 2015-03-02
      相关资源
      最近更新 更多