想要通过父元素覆盖子元素的 css 属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21297085/
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
Want to override child element css property by parent element
提问by user3225796
<div class="parent">
<div class="child">
</div></div>
In CSS, "child" class has its own bg color, that I can't change. I want to apply "parent" class bg color to container. So, Is there any CSS trick to override "child" bg color by "parent" bg color.
在 CSS 中,“child”类有自己的 bg 颜色,我无法更改。我想将“父”类 bg 颜色应用于容器。那么,是否有任何 CSS 技巧可以通过“父”bg 颜色覆盖“子”bg 颜色。
Any help would be much appreciated.
任何帮助将非常感激。
Thanks
谢谢
回答by Cam
!important will override any inline background color applied, let me know if this works
!important 将覆盖任何应用的内嵌背景颜色,让我知道这是否有效
.parent > .child {
background-color: transparent !important;
}
回答by rvighne
.parent .child {
background-color: inherit !important; // can also use "transparent"
}
Use !important
only if nothing else works.
!important
仅在没有其他效果时才使用。
回答by Marcatectura
You could override the CSS using jQuery, although it's inelegant. So, if you have HTML
您可以使用 jQuery 覆盖 CSS,尽管它不雅。所以,如果你有 HTML
<div class="parent">
<div class="child">
</div></div>
and CSS:
和 CSS:
.parent {
width: 100px;
height: 100px;
background: red;
}
.child {
width: 50px;
height: 50px;
background: blue;
}
this jQuery will find the parent background color and apply it to the child:
这个 jQuery 将找到父背景颜色并将其应用到孩子:
$('.child').on('click', function(event) {
var bg = $(this).parent().css("background-color"); // finds background color of parent
$(this).css("background-color", bg); // applies background color to child
});
Here's a jsfiddle: link
这是一个jsfiddle:链接