css - 如何扩展具有动态形成的选择器的类/mixin

标签 css less less-mixins

如何扩展使用 & 组合器动态形成的 Less 类?

生成预期输出的 Less:

.hello-world {
  color: red;
}

.foo {
  &:extend(.hello-world);
  font-size: 20px;
}

预期的 CSS 输出:

.hello-world,
.foo {
  color: red;
}
.foo {
  font-size: 20px;
}

Less 不会产生预期的输出:

.hello {
  &-world {
    color: red;
  }
}

.foo {
  &:extend(.hello-world);
  font-size: 20px;
}

意外的 CSS 输出:

.hello-world {
  color: red;
}
.foo {
  font-size: 20px;
}

最佳答案

像这样扩展动态形成的选择器(松散地使用该术语)目前在 Less 中是不可能的。有一个开放的feature request支持这一点。在实现之前,这里有两个解决方案。

选项 1:

.hello.hello-world选择器的内容写入一个单独的Less文件(比如test.less),编译它获取CSS。为 .foo 的规则创建另一个文件,将编译后的 CSS 作为 Less 文件导入(使用 (less) 指令),然后扩展 .hello-世界,正如你最初想要的那样。

test.less:

.hello {
  &-world {
    color: red;
  }
}

extended-rule.less:

@import (less) "test.css";
.foo {
  &:extend(.hello-world);
  font-size: 20px;
}

编译后的 CSS:

.hello-world,
.foo {
  color: red;
}
.foo {
  font-size: 20px;
}

此方法可行,因为在导入 test.css 文件时,选择器已经形成并且不再是动态的。缺点是它需要一个额外的文件并产生依赖性。


选项 2:

为需要应用于 .hello-world.foo 的所有属性编写一个带有规则的虚拟选择器,并将其扩展为:

.dummy{
    color: red;
}
.hello {
  &-world:extend(.dummy) {};
}

.foo:extend(.dummy){
  font-size: 20px;
}

这会创建一个额外的选择器(虚拟),但差别不大。

注意:添加我的评论作为答案是为了不让问题悬而未决,而且因为在评论中链接的线程中指定的解决方法对我来说并不适用。

关于css - 如何扩展具有动态形成的选择器的类/mixin,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24879871/

相关文章:

html - 如何将图像制作成链接

javascript - 来自波浪线 svg 的连续波浪动画

twitter-bootstrap - Bootstrap 3 翻译混入

css - LESS CSS - 在 mixin 中设置变量

css - 如何在 less mixin 中访问特定的类属性?

css - 如何覆盖 AMP 页面中的内联样式?

javascript - jquery ui 可排序垃圾箱显示和隐藏事件

css - 在媒体查询中使用 LESS 变量

css - 如何将div居中到窗口?

html - 我的 css 高度自动不起作用