如何使一个元素继承另一个元素的一组CSS规则?
假设我有一个
div.someBaseDiv {
margin-top: 3px;
margin-left: auto;
margin-right: auto;
margin-bottom: 0px;
}
我想这样继承:
div.someBaseDiv someInheritedDiv {
background-image: url("images/worldsource/customBackground.gif");
background-repeat: no-repeat;
width: 950px;
height: 572px;
}
当然,我很确定这是写错了,而且我不害怕寻求帮助,所以有人可以告诉我如何进行这项工作并包括HTML标记吗?
jazzBox asked 2020-06-18T16:50:38Z
6个解决方案
65 votes
最简单的方法是将someInheritedDiv元素添加到第一个规则中,如下所示。
div.someBaseDiv,
#someInheritedDiv
{
margin-top:3px;
margin-left:auto;
margin-right:auto;
margin-bottom:0px;
}
这将告诉您的#someInheritedDiv应用与div.someBaseDiv相同的样式。 然后,将这组样式扩展为更特定于#someInheritedDiv:
#someInheritedDiv
{
background-image:url("images/worldsource/customBackground.gif");
background-repeat:no-repeat;
width:950px;
height:572px;
}
这就是CSS中的特异性的工作方式。
spliter answered 2020-06-18T16:51:01Z
20 votes
使用这两个类,并像这样组合它们:
.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;
}
标记如下:
现在,如果需要,您可以以这种方式覆盖baseClass……并且由于您不必一直将新的类名添加到baseClass定义中,因此更加干净。
canon answered 2020-06-18T16:51:30Z
13 votes
对于此任务,我建议您使用称为LESS的功能强大的CSS扩展。 它可以编译成CSS,也可以与javascript文件一起即时使用,如链接所述。
如您所描述的那样,LESS(几乎)支持继承。 该文档包含详细信息(请参阅“ Mixins”部分)。
对于您的示例,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;
}
请注意,它必须是.someBaseDiv,而不是div.someBaseDiv
Alan Turing answered 2020-06-18T16:52:04Z
7 votes
您要做的是使一些CSS应用于两种不同类型的元素,但也允许它们具有一些差异。 您可以使用一些简单的HTML来做到这一点:
和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;
}
这会将共享属性添加到div的两种类型,但是特定属性仅添加到派生的divs
Kyle Sletten answered 2020-06-18T16:52:32Z
3 votes
那真的取决于您的标记。 如果您的继承元素位于类someBaseDiv的div下,则该元素的所有子元素将自动继承这些属性。
但是,如果您想在标记中的任何地方继承someBaseDiv类,则可以只使要继承的元素,使用这两个类:
和您的CSS将是这样的:
div.someBaseDiv
{
margin-top:3px;
margin-left:auto;
margin-right:auto;
margin-bottom:0px;
}
div.someInheritedDiv
{
background-image:url("images/worldsource/customBackground.gif");
background-repeat:no-repeat;
width:950px;
height:572px;
}
Niklas answered 2020-06-18T16:53:02Z
2 votes
如果您希望所有具有特定类的内部DIV都可以从基类继承,请构建HTML标记,如下所示:
和CSS
.parent { border: 2px solid red; color: white }
.parent .child { background: black }
如果所有DIV必须继承,请将someClass更改为div。
请参阅jsFiddle上的示例
以下代码
// parent // all DIVs inside the parent
.someClass div { }
意思是:类为someClass的top元素(任何)将样式添加到其所有子DIV(递归)。
BrunoLM answered 2020-06-18T16:53:44Z