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

例如,假设我们有:

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

我想做的是:

.composite 
{
   .something;
   .else
}

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


当前回答

看看CSS合成:https://bambielli.com/til/2017-08-11-css-modules-composes/

根据他们的说法:

.serif-font {
    font-family: Georgia, serif;
}

.display {
    composes: serif-font;
    font-size: 30px;
    line-height: 35px;
}

我在我的反应项目中使用它。

其他回答

这在CSS中是不可能的。

CSS中唯一支持的是比另一条规则更具体:

span { display:inline }
span.myclass { background: red }

类为“myclass”的span将同时具有这两个财产。

另一种方法是指定两个类:

<div class="something else">...</div>

“else”的样式将覆盖(或添加)“something”的样式

不,你不能这样做

.composite 
{
   .something;
   .else
}

这不是OO意义上的“类”名称。something和.else只是选择器而已。

但是您可以在一个元素上指定两个类

<div class="something else">...</div>

或者你可以研究另一种形式的继承

.foo {
  background-color: white;
  color: black;
}

.bar {
  background-color: inherit;
  color: inherit;
  font-weight: normal;
}
<div class="foo">
  <p class="bar">Hello, world</p>
</div>

其中段落背景颜色和颜色继承自封闭div中的设置,该div为.foo样式。您可能需要检查确切的W3C规范。无论如何,inherit是大多数财产的默认值,但不是所有属性的默认值。

在Css文件中:

p.Title 
{
  font-family: Arial;
  font-size: 16px;
}

p.SubTitle p.Title
{
   font-size: 12px;
}

我认为这是一个更好的解决方案:

[class*=“button-“] {
  /* base button properties */
}
.button-primary { ... }
.button-plain { ... }

您可以使用相反的方法来实现相同的结果-从复合开始,然后使用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%的未设置关键字支持率下,浏览器覆盖率非常高。