从父div到子div继承所有css属性

Nis*_*ede 3 html javascript css jquery

我的HTML,

<div id="parent">
    <div id="child">

    </div>

</div>
Run Code Online (Sandbox Code Playgroud)

css看起来像,

#parent{
height:100px;
width:200px;
any-aother-property1:something;
any-aother-property2:something;
any-aother-property3:something;
}
Run Code Online (Sandbox Code Playgroud)

是否有任何方法可以立即将所有属性继承到子级,我可以这样做,

$('#child').properties= $('#parent').properties
Run Code Online (Sandbox Code Playgroud)

cam*_*ous 9

如果你真的想动态继承所有在运行时赋予父级的 CSS 属性,你可以执行以下操作。

注意:这会覆盖所有属性的默认值。一般来说,明智的做法是假设默认值是正确的,除非另有证明。有些属性是inherit默认的,有些不是因为各种原因。因此,您可能应该只覆盖需要更改的特定属性。

#child {
    all: inherit;
}
Run Code Online (Sandbox Code Playgroud)


mik*_*vck 5

这够了吗?

#parent, #parent > div {
    /* your properties */
}
Run Code Online (Sandbox Code Playgroud)

  • @ Flopet17因为css中的id是邪恶的.我宁愿做#parent,#parent .inheritStyle {...}.并将class ='inheritStyle'添加到子级.或者甚至更好地通过css给他们class ='myStyle'和样式.myStyle. (2认同)

Flo*_*Pop 1

据我所知,没有这样的事情,但你总是可以这样做:

#parent, #child{
    height:100px;
    width:200px;
    any-aother-property1:something;
    any-aother-property2:something;
    any-aother-property3:something;
}
Run Code Online (Sandbox Code Playgroud)

添加两个 id 以具有相同的属性。