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

例如,假设我们有:

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

我想做的是:

.composite 
{
   .something;
   .else
}

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


当前回答

事实上,你所要求的是存在的——但它是作为附加模块完成的。查看有关.NET中更好的CSS的示例。

查看Larsenal关于使用LESS的回答,了解这些附加组件的功能。

其他回答

给定示例的SCSS方式如下:

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

.composite {
  @extend .something;
  @extend .else;
}

更多信息,请查看sass基础知识

有一些类似LESS的工具,它允许您在类似于所描述的更高抽象级别上编写CSS。

更少的人称这些为“混合”

而不是

/* CSS */
#header {
  -moz-border-radius: 8px;
  -webkit-border-radius: 8px;
  border-radius: 8px;
}

#footer {
  -moz-border-radius: 8px;
  -webkit-border-radius: 8px;
  border-radius: 8px;
}

你可以说

/* LESS */
.rounded_corners {
  -moz-border-radius: 8px;
  -webkit-border-radius: 8px;
  border-radius: 8px;
}

#header {
  .rounded_corners;
}

#footer {
  .rounded_corners;
}

不,你不能这样做

.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是大多数财产的默认值,但不是所有属性的默认值。

不要忘记:

div.something.else {

    // will only style a div with both, not just one or the other

}

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

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

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

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