Have 2 classes as parent selectors at different levels in Less?

╄→гoц情女王★ 提交于 2019-12-24 15:40:09

问题


I need this CSS:

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

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

I've got this working fine with this Less

.target {

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

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

However can my LESS be written more succinctly? Its seems a shame to write class-1 twice. I've tried this:

.target {

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

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

And also this:

.target {

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

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

回答1:


Your last attempt is pretty close, if you modify it like:

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

it will work.

Note that the order of classes of the same level does not matter, thus the resulting .class-a.class-1 .target is equal to desired .class-1.class-a .target

(I'm not mentioning though that usually the idea of avoiding repetitions by any cost is flawed. All those cryptic chains of ampersands and brackets make the code totally unreadable if compared to your initial code and even pure CSS itself).



来源:https://stackoverflow.com/questions/34727945/have-2-classes-as-parent-selectors-at-different-levels-in-less

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!