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

例如,假设我们有:

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

我想做的是:

.composite 
{
   .something;
   .else
}

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


当前回答

有一些类似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;
}

其他回答

不要忘记:

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>

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

我遇到了同样的问题,最后使用了JQuery解决方案,使类看起来可以继承其他类。

<script>
    $(function(){
            $(".composite").addClass("something else");
        });
</script>

这将查找具有类“composite”的所有元素,并将类“something”和“else”添加到元素中。所以类似于<div class=“composite”></div>将这样结束:<div class=“composite something other”></分区>

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

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

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

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

你能做的就是这个

CSS

.car {
  font-weight: bold;
}
.benz {
  background-color: blue;
}
.toyota {
  background-color: white;
}

HTML

<div class="car benz">
  <p>I'm bold and blue.</p>
</div>
<div class="car toyota">
  <p>I'm bold and white.</p>
</div>