动态地从CSS内部分配一个CSS类

4

有没有可能动态地给现有的类分配一个类?我正在尝试为第一个子元素分配样式,就像这样:

.active {
  color: red;
}

item:first-child .item_text {
  background: rgba(255, 255, 255, 1);
  /* make it active class */
}
1个回答

3
不,仅使用CSS是不可能实现这一点的。
你所能做到的最好的方式是:
.active,
item:first-child .item_text {
  color: red;
}

item:first-child .item_text {
  background: rgba(255, 255, 255, 1);
}

如果您使用像LESS或SASS这样的CSS预处理器,就可以实现这一点。它们可以扩展CSS的功能,例如包含/扩展类等。

在LESS中

item:first-child .item_text {
  background: rgba(255, 255, 255, 1);
  .active;
}

这将直接替换该类名为color: red;行。
在SASS中(从版本3开始,使用“SCSS”语法):
item:first-child .item_text {
  background: rgba(255, 255, 255, 1);
  @extend .active;
}

这将产生与我上面CSS示例相同的输出结果。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接