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

例如,假设我们有:

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

我想做的是:

.composite 
{
   .something;
   .else
}

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


当前回答

你能做的就是这个

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>

其他回答

不要忘记:

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>

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

对于那些对上述(优秀)文章不满意的人,您可以使用编程技能创建一个变量(PHP或任何一个),并让它存储多个类名。

这是我能想出的最好的办法。

<style>
.red { color: red; }
.bold { font-weight: bold; }
</style>

<? define('DANGERTEXT','red bold'); ?>

然后将全局变量应用于所需的元素,而不是类名本身

<span class="<?=DANGERTEXT?>"> Le Champion est Ici </span>

而直接继承是不可能的。

可以为父标记使用类(或id),然后使用CSS组合符改变子标记的继承行为。

p.test{背景色:rgba(55,55,55,0.1);}p.test>span{背景色:rgba(55,55,55,0.1);}p.test>span>span{背景色:rgba(55,55,55,0.1);}p.test>span>span>span{背景色:rgba(55,55,55,0.1);}p.test>span>span>span{背景色:rgba(55,55,55,0.1);}p.test/span>span>span>span{背景色:rgba(55,55,55,0.1);}p.test/span>span>span>span>span{背景色:rgba(55,55,55,0.1);}p.test>span>span>/span>span>span{背景色:rgba(55,55,55,0.1);}p.test>span>span>span>span>span>span>span{背景色:rgba(55,55,55,0.1);}<p class=“test”><span>一种可能的<span>解决方案<span>是使用<span>多个<span>嵌套<span>标记</span></span><span></span></span></p>

我不建议像示例那样使用这么多跨度,但这只是概念的证明。当试图以这种方式应用CSS时,仍然会出现许多错误。(例如,更改文本装饰类型)。

将常用属性放在一起,然后再次指定特定(或覆盖)属性。

/*  ------------------------------------------------------------------------------ */   
/*  Headings */ 
/*  ------------------------------------------------------------------------------ */   
h1, h2, h3, h4
{
    font-family         : myfind-bold;
    color               : #4C4C4C;
    display:inline-block;
    width:900px;
    text-align:left;
    background-image: linear-gradient(0,   #F4F4F4, #FEFEFE);/* IE6 & IE7 */
}

h1  
{
    font-size           : 300%;
    padding             : 45px 40px 45px 0px;
}

h2
{
    font-size           : 200%;
    padding             : 30px 25px 30px 0px;
}