CSS 如何将样式应用于元素的所有子元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26349987/
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
How do I apply a style to all children of an element
提问by MTilsted
I have an element with class='myTestClass'
. How do I apply a css style to all children of this elements? I only want to apply the style to the elements children. Not its grand children.
我有一个带有class='myTestClass'
. 如何将 css 样式应用于此元素的所有子元素?我只想将样式应用于元素子项。不是它的孙子。
I could use
我可以用
.myTestClass > div {
margin: 0 20px;
}
which work for all div
children, but I would like a solution which works for all children. I thought I could use *
, but
适用于所有div
儿童,但我想要一个适用于所有儿童的解决方案。我以为我可以用*
,但是
.myTestClass > * {
margin: 0 20px;
}
does not work.
不起作用。
Edit
编辑
The .myTestClass > *
selector does not apply the rule in firefox 26, and there is no other rule for margin according to firebug. And it works if I replace *
with div
.
该.myTestClass > *
选择不使用Firefox 26应用规则,并有根据萤火没有其他规则的保证金。如果我替换*
为div
.
回答by Anonymous
As commented by David Thomas, descendants of those child elements will (likely) inherit most of the styles assigned to those child elements.
正如David Thomas评论的那样,这些子元素的后代将(可能)继承分配给这些子元素的大部分样式。
You need to wrap your .myTestClass
inside an element and apply the styles to descendants by adding .wrapper *
descendant selector. Then, add .myTestClass > *
child selectorto apply the style to the elements children, not its grand children. For example like this:
您需要将您.myTestClass
的元素包装在一个元素中,并通过添加.wrapper *
后代选择器将样式应用于后代。然后,添加.myTestClass > *
子选择器以将样式应用于元素子元素,而不是其孙子元素。例如像这样:
JSFiddle - DEMO
JSFiddle -演示
.wrapper * {
color: blue;
margin: 0 100px; /* Only for demo */
}
.myTestClass > * {
color:red;
margin: 0 20px;
}
<div class="wrapper">
<div class="myTestClass">Text 0
<div>Text 1</div>
<span>Text 1</span>
<div>Text 1
<p>Text 2</p>
<div>Text 2</div>
</div>
<p>Text 1</p>
</div>
<div>Text 0</div>
</div>
回答by JPB
Instead of the *
selector you can use the :not(selector)
with the >
selector and set something that definitely wont be a child.
取而代之的是的*
选择,你可以使用:not(selector)
与>
选择器和一套东西,绝对不会是一个孩子。
Edit: I thought it would be faster but it turns out I was wrong. Disregard.
编辑:我认为它会更快,但事实证明我错了。漠视。
Example:
例子:
.container > :not(marquee){
color:red;
}
<div class="container">
<p></p>
<span></span>
<div>