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

例如,假设我们有:

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

我想做的是:

.composite 
{
   .something;
   .else
}

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


当前回答

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

/*  ------------------------------------------------------------------------------ */   
/*  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;
}

其他回答

我认为这是一个更好的解决方案:

[class*=“button-“] {
  /* base button properties */
}
.button-primary { ... }
.button-plain { ... }

不要将css类视为面向对象的类,将它们视为其他选择器中的一个工具,用于指定html元素的样式。将大括号之间的所有内容视为属性类,左侧的选择器告诉它们选择的元素从属性类继承属性。例子:

.foo, .bar { font-weight : bold; font-size : 2em; /* attribute class A */}
.foo { color : green; /* attribute class B */}

当一个元素被赋予属性class=“foo”时,最好不要将其看作是从class.foo继承属性,而是从属性class A和属性class B继承属性。也就是说,继承图是一个层次,元素从属性class派生,选择器指定边的位置,以及当存在竞争属性时确定优先级(类似于方法解析顺序)。

编程的实际含义是这样的。假设您有上面给出的样式表,并希望添加一个新的类.baz,其中它应该具有与.foo相同的字体大小。最简单的解决方案是:

.foo, .bar { font-weight : bold; font-size : 2em; /* attribute class A */}
.foo { color : green; /* attribute class B */}
.baz { font-size : 2em; /* attribute class C, hidden dependency! */}

每当我要打两次字时,我都会很生气!我不仅要写两次,现在我没有办法用程序表示.foo和.baz应该具有相同的字体大小,而且我创建了一个隐藏的依赖项!我的上述范例建议我应该从属性类A中抽象出字体大小属性:

.foo, .bar, .baz { font-size : 2em; /* attribute base class for A */}
.foo, .bar { font-weight : bold; /* attribute class A */}
.foo { color : green; /* attribute class B */}

这里的主要抱怨是,现在我必须再次键入属性类A中的每个选择器,以指定它们应该选择的元素也应该继承属性基类A中的属性。然而,替代方法是,必须记住在每次发生更改时编辑每个存在隐藏依赖项的属性类,或者使用第三方工具。第一个选项让上帝发笑,第二个选项让我想自杀。

正如其他人所说,您可以向一个元素添加多个类。

但这不是真正的重点。我明白你关于遗产的问题。真正的问题是CSS中的继承不是通过类来实现的,而是通过元素层次结构来实现的。因此,要对继承的特性进行建模,需要将它们应用于DOM中不同级别的元素。

有一些类似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
{
display:inherit;
background:inherit;
}

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

这仅在将.composite类添加到子元素时有效。它是“软”继承,因为任何未在.composite中指定的值都不会明显继承。请记住,简单地写“inline”和“red”而不是“inherit”仍然会减少字符数。

以下是财产列表,以及它们是否自动执行此操作:https://www.w3.org/TR/CSS21/propidx.html