本文介绍了在Less中,有2个类作为不同级别的父选择器吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要这个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可以更简洁地编写吗?两次写1级课程似乎很可耻.我已经尝试过了:

.target {

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

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

还有:

.target {

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

    .class-b & {
      background: blue;
    }
  }
}
解决方案

如果您进行如下修改,您的最后一次尝试就非常接近了:

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

它将起作用.

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

(我没有提到,尽管通常不惜一切代价避免重复的想法是有缺陷的.与起始代码甚至纯CSS本身相比,所有这些与号和方括号的神秘链使代码完全不可读). /p>

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;
    }
  }
}
解决方案

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).

这篇关于在Less中,有2个类作为不同级别的父选择器吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-21 23:15