是否可以创建一个从另一个CSS类(或多个)“继承”的CSS类。
例如,假设我们有:
.something { display:inline }
.else { background:red }
我想做的是:
.composite
{
.something;
.else
}
其中“.composite”类将显示为内联,并具有红色背景
是否可以创建一个从另一个CSS类(或多个)“继承”的CSS类。
例如,假设我们有:
.something { display:inline }
.else { background:red }
我想做的是:
.composite
{
.something;
.else
}
其中“.composite”类将显示为内联,并具有红色背景
当前回答
如果您想要比LESS更强大的文本预处理器,请查看PPWizard:
http://dennisbareis.com/ppwizard.htm
警告:该网站确实很难看,学习曲线很小,但它非常适合通过宏构建CSS和HTML代码。我一直不明白为什么更多的网络程序员不使用它。
其他回答
您可以使用相反的方法来实现相同的结果-从复合开始,然后使用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%的未设置关键字支持率下,浏览器覆盖率非常高。
一个元素可以包含多个类:
.classOne { font-weight: bold; }
.classTwo { font-famiy: verdana; }
<div class="classOne classTwo">
<p>I'm bold and verdana.</p>
</div>
不幸的是,这几乎和你会得到的一样接近。我希望有一天能看到这个特性以及类别名。
完美的时机:我从这个问题转到了我的电子邮件,找到了一篇关于Less的文章,这是一个Ruby库,除其他外,它还做了以下工作:
由于super看起来就像页脚,但字体不同,所以我将使用Less的类包含技术(他们称之为mixin)来告诉它也包含这些声明:
#super {
#footer;
font-family: cursive;
}
我意识到这个问题已经很老了,但是,这里什么都没有!
如果目的是添加一个包含多个类的财产的类作为本机解决方案,我建议使用JavaScript/jQuery(jQuery确实不是必需的,但确实很有用)
例如,如果您有从.baseClass1和.baseClass2“继承”的.bumbellaClass,则可以有一些JavaScript在就绪时启动。
$(".umbrellaClass").addClass("baseClass1");
$(".umbrellaClass").addClass("baseClass2");
现在.umbrellaClass的所有元素都将具有.baseClasss的所有财产。请注意,与OOP继承一样,.umbrellaClass可能有也可能没有自己的财产。
这里唯一需要注意的是,是否有动态创建的元素在代码触发时不存在,但也有简单的方法可以解决。
不过,Sucks css没有原生继承。
对于那些对上述(优秀)文章不满意的人,您可以使用编程技能创建一个变量(PHP或任何一个),并让它存储多个类名。
这是我能想出的最好的办法。
<style>
.red { color: red; }
.bold { font-weight: bold; }
</style>
<? define('DANGERTEXT','red bold'); ?>
然后将全局变量应用于所需的元素,而不是类名本身
<span class="<?=DANGERTEXT?>"> Le Champion est Ici </span>