是否可以创建一个从另一个CSS类(或多个)“继承”的CSS类。

例如,假设我们有:

.something { display:inline }
.else      { background:red }

我想做的是:

.composite 
{
   .something;
   .else
}

其中“.composite”类将显示为内联,并具有红色背景


当前回答

您可以使用相反的方法来实现相同的结果-从复合开始,然后使用unset关键字删除样式。例如,如果从以下示例组成开始:

.composite {
    color: red;
    margin-left: 50px;
    background-color: green
}

然后可以增加选择器的特异性,以使用unset选择性地删除样式:

.composite.no-color {
    color: unset
}

.composite.no-margin-left {
    margin-left: unset
}

.composite.no-background-color {
    background-color: unset
}

这里有一个JSFiddle演示了这种方法。

这种方法的一个好处是,由于复合选择器的特异性高于复合选择器本身,因此不需要所有类的组合来实现多个组合的预期结果:

/* Multi-unset compound selector combinations, such as the one that follows, ARE NOT NECESSARY because of the higher specificity of each individual compound selectors listed above. This keeps things simple. */
.composite.no-background-color.no-color.no-margin-left {
    background-color: unset;
    color: unset;
    margin-left: unset
}

此外,在96%的未设置关键字支持率下,浏览器覆盖率非常高。

其他回答

是的,但不完全符合这个语法。

.composite,
.something { display:inline }

.composite,
.else      { background:red }

您可以使用相反的方法来实现相同的结果-从复合开始,然后使用unset关键字删除样式。例如,如果从以下示例组成开始:

.composite {
    color: red;
    margin-left: 50px;
    background-color: green
}

然后可以增加选择器的特异性,以使用unset选择性地删除样式:

.composite.no-color {
    color: unset
}

.composite.no-margin-left {
    margin-left: unset
}

.composite.no-background-color {
    background-color: unset
}

这里有一个JSFiddle演示了这种方法。

这种方法的一个好处是,由于复合选择器的特异性高于复合选择器本身,因此不需要所有类的组合来实现多个组合的预期结果:

/* Multi-unset compound selector combinations, such as the one that follows, ARE NOT NECESSARY because of the higher specificity of each individual compound selectors listed above. This keeps things simple. */
.composite.no-background-color.no-color.no-margin-left {
    background-color: unset;
    color: unset;
    margin-left: unset
}

此外,在96%的未设置关键字支持率下,浏览器覆盖率非常高。

正如其他人所说,您可以向一个元素添加多个类。

但这不是真正的重点。我明白你关于遗产的问题。真正的问题是CSS中的继承不是通过类来实现的,而是通过元素层次结构来实现的。因此,要对继承的特性进行建模,需要将它们应用于DOM中不同级别的元素。

一个元素可以包含多个类:

.classOne { font-weight: bold; }
.classTwo { font-famiy:  verdana; }

<div class="classOne classTwo">
  <p>I'm bold and verdana.</p>
</div>

不幸的是,这几乎和你会得到的一样接近。我希望有一天能看到这个特性以及类别名。

您可以向单个DOM元素添加多个类,例如。

<div class="firstClass secondClass thirdclass fourthclass"></div>

后面的类(或更具体的类)中给出的规则将覆盖。所以这个例子中的第四类占了上风。

继承不是CSS标准的一部分。