Mixin 以不同方式对待 2 个相等 class 定义

Mixin treat 2 equal class definitions differently

我从一个简单的例子开始:

.classA {
  color: red;
  .otherClass {
       color: yellow;
  }
}
.classB {
  .classA;
}

结果:

.classA {
  color: red;
}
.classA .otherClass {
  color: yellow;
}
.classB {
  color: red;
}
.classB .otherClass {
  color: yellow;
}

但是:

.classA {
  color: red;
}
.class A .otherClass {
  color: yellow;
}
.classB {
  .classA;
}

结果:

.classA {
  color: red;
}
.class A .otherClass {
  color: yellow;
}
.classB {
  color: red;
}

我不明白为什么编译器不在 .classB 中包含 .otherClass。我的意思是 classA 两个定义是相等的,不是吗?

对于奇怪的行为有简单的解释吗? 特别是,有没有办法通过 mixin 包含 .otherClass 或我是否必须复制代码?

I mean both classA definitions are equal aren't they?

不,它们确实创建了相等的 CSS selectors/rulesets,但是它们的 Less 定义 是完全不同的(实际上它是一个 Less 规则集定义第一个片段,第二个片段中有两个独立的规则集定义。

换句话说: Mixins 工具不能以类似 HTML 的方式与 selectors 一起工作(是的,一开始这可能令人惊讶)。 Mixin 使用 规则集 及其 scope,因此 mixin 扩展规则非常简单:

.foo will match .foo ruleset(s) only (and expand all code defined inside that .foo only)

因此任何单独定义的 .foo .bar 等规则集从不涉及 .foo 调用。 (是的,CSS 选择器最后的结果并不重要。唯一的例外是 namespaces,但这是另一个大故事,我不想让你混淆)。

对于您的特定示例,我会说 extend 更合适。