如何将样式应用于元素的所有子元素 [英] How do I apply a style to all children of an element
问题描述
我有一个带class='myTestClass'
的元素.如何将CSS样式应用于此元素的所有子元素?我只想将样式应用于子元素.不是大孩子.
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.
我可以使用
.myTestClass > div {
margin: 0 20px;
}
适用于所有div
儿童,但是我想要一个适用于所有儿童的解决方案.我以为我可以使用*
,但是
which work for all div
children, but I would like a solution which works for all children. I thought I could use *
, but
.myTestClass > * {
margin: 0 20px;
}
不起作用.
编辑
.myTestClass > *
选择器不会在firefox 26中应用该规则,并且根据firebug没有其他用于边距的规则.如果我将*
替换为div
,则此方法有效.
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
.
推荐答案
As commented by David Thomas, descendants of those child elements will (likely) inherit most of the styles assigned to those child elements.
您需要将.myTestClass
包装在一个元素内,然后通过添加.wrapper *
子选择器,以将样式应用于元素的孩子,而不是其大孩子.例如这样的
You need to wrap your .myTestClass
inside an element and apply the styles to descendants by adding .wrapper *
descendant selector. Then, add .myTestClass > *
child selector to apply the style to the elements children, not its grand children. For example like this:
JSFiddle-演示
JSFiddle - DEMO
.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>
这篇关于如何将样式应用于元素的所有子元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!