CSS继承

jaz*_*Box 48 css

假设我有一个<div>这样的背景图像具有所有相同的属性或类似的东西:

div.someBaseDiv {
    margin-top: 3px;
    margin-left: auto;
    margin-right: auto;
    margin-bottom: 0px;
}
Run Code Online (Sandbox Code Playgroud)

我想继承它:

div.someBaseDiv someInheritedDiv {
    background-image: url("images/worldsource/customBackground.gif");
    background-repeat: no-repeat;
    width: 950px;
    height: 572px;
}
Run Code Online (Sandbox Code Playgroud)

当然我很确定这是错误的,我也不害怕寻求帮助,有人能告诉我如何使这项工作并包含HTML标记吗?

spl*_*ter 66

最简单的方法是将someInheritedDiv元素添加到第一个规则中.

div.someBaseDiv,
#someInheritedDiv
{
    margin-top:3px;
    margin-left:auto;
    margin-right:auto;
    margin-bottom:0px;
}
Run Code Online (Sandbox Code Playgroud)

这将告诉你的#someInheritedDiv应用与div.someBaseDiv相同的样式.然后,您这些样式扩展为更具体的#someInheritedDiv:

#someInheritedDiv
{
    background-image:url("images/worldsource/customBackground.gif");
    background-repeat:no-repeat;
    width:950px;
    height:572px;
}
Run Code Online (Sandbox Code Playgroud)

这就是CSS的特殊性.


I a*_*ica 20

使用这两个类并将它们组合如下:

.baseClass
{
    margin-top:3px;
    margin-left:auto;
    margin-right:auto;
    margin-bottom:0px;
}

.baseClass.otherClass /* this means the element has both baseClass and otherClass */
{
    background-image:url("images/worldsource/customBackground.gif");
    background-repeat:no-repeat;
    width:950px;
    height:572px;
}
Run Code Online (Sandbox Code Playgroud)

标记如下:

<div class="baseClass otherClass"></div>
Run Code Online (Sandbox Code Playgroud)

现在,以这种方式,您可以在必要时覆盖baseClass ...并且由于您不必继续将新类名添加到baseClass定义中,因此它更清晰一些.


Ala*_*ing 13

对于此任务,我建议您使用名为LESS的强大CSS扩展.它可以编译成CSS,或者可以在链接解释时使用javascript文件即时使用.

LESS支持继承(几乎),如您所述.该文件有详细资料(请参见"混入").

对于您的示例,LESS代码将是:

.someBaseDiv {
    margin-top:3px;
    margin-left:auto;
    margin-right:auto;
    margin-bottom:0px;
}

someInheritedDiv {
    .someBaseDiv;

    background-image:url("images/worldsource/customBackground.gif");
    background-repeat:no-repeat;
    width:950px;
    height:572px;
}
Run Code Online (Sandbox Code Playgroud)

请注意,它必须是,.someBaseDiv而不是div.someBaseDiv

  • 只是一个注释 - LESS根本不是CSS的扩展.它是用Javascript编写的预处理器. (18认同)

Kyl*_*ten 7

你想要做的是让一些CSS适用于两种不同类型的元素,但也允许它们有一些差异.你可以使用一些简单的HTML来做到这一点:

<div class="base">
    <div class"inherited">
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

和CSS:

.base, .inherited{
    margin-top:3px;
    margin-left:auto;
    margin-right:auto;
    margin-bottom:0px;
}

.inherited{
    background-image:url("images/worldsource/customBackground.gif");
    background-repeat:no-repeat;
    width:950px;
    height:572px;
}
Run Code Online (Sandbox Code Playgroud)

这会将共享属性添加到两种类型div,但仅将特定的属性添加到派生的divs