Html 强制子 div 使用父样式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7517885/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Forcing child divs to use parent's style
提问by user893970
I wanted to give all of the child's div elements a background-color of parent div. But, as I see, child divs' style overwrite parent's style even though child's did not have that property. For example,
我想给所有孩子的 div 元素一个父 div 的背景颜色。但是,正如我所看到的,即使孩子没有该属性,孩子 div 的样式也会覆盖父母的样式。例如,
<!-- Parent's div -->
<div style="background-color:#ADADAD;">
some codes here...
<!-- child's div -->
<div style="position:absolute;font-size:12px; left:600px;top:100px;">
again some codes...
</div>
</div>
In here, If i delete the style of child div, it works fine. I think my problem may be solved if i did the same thing with external css file also. But, I have already done hundreds of divs exactly like this. So, is there anyway to force parent's style to child style, just for background-color?(new in css)
在这里,如果我删除子 div 的样式,它工作正常。我认为如果我对外部 css 文件也做同样的事情,我的问题可能会得到解决。但是,我已经像这样完成了数百个 div。那么,是否有任何方式将父样式强制为子样式,仅用于背景颜色?(css 中的新功能)
采纳答案by Quentin
But, as i see, chid divs' style overwrite parent's style even though child's did not have that property.
但是,正如我所看到的,即使孩子没有该属性,chid div 的样式也会覆盖父母的样式。
No, they just don't inherit the value by default, so they get whatever value they would otherwise have (which is usually transparent
).
不,它们只是默认不继承该值,因此它们会获得本来具有的任何值(通常是transparent
)。
You can (in theory) get what you want with background-color: inherit. That has problems in older versions of IEthough.
回答by Hossein
Use css selectors like this to make the background of child div's inherit from their parent:
使用像这样的 css 选择器使子 div 的背景从其父级继承:
Parent's div
<div id="thisparticulardiv">
some codes here...
child's div
<div class="childrendiv">
again some codes...
</div></div>
CSS:
CSS:
#thisparticulardiv {
background-color:#ADADAD;
...
}
#thisparticulardiv div {
background: inherit;
position:absolute;
font-size:12px;
left:600px;
top:100px;
}
回答by Kraz
Use the inherit property on the child div :
在子 div 上使用继承属性:
background:inherit
<div style="position:absolute;font-size:12px; left:600px;top:100px; background:inherit">