是否可以创建一个从另一个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的工具,它允许您在类似于所描述的更高抽象级别上编写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是大多数财产的默认值,但不是所有属性的默认值。
给定示例的SCSS方式如下:
.something {
display: inline
}
.else {
background: red
}
.composite {
@extend .something;
@extend .else;
}
更多信息,请查看sass基础知识
在特定情况下,可以执行“软”继承:
.composite
{
display:inherit;
background:inherit;
}
.something { display:inline }
.else { background:red }
这仅在将.composite类添加到子元素时有效。它是“软”继承,因为任何未在.composite中指定的值都不会明显继承。请记住,简单地写“inline”和“red”而不是“inherit”仍然会减少字符数。
以下是财产列表,以及它们是否自动执行此操作:https://www.w3.org/TR/CSS21/propidx.html
不要忘记:
div.something.else {
// will only style a div with both, not just one or the other
}
我也在疯狂地寻找它,我只是通过尝试不同的东西来找到它:P。。。你可以这样做:
composite.something, composite.else
{
blblalba
}
它突然对我奏效了:)