如何对元素的所有子元素应用样式 [英] How do I apply a style to all children of an elements
问题描述
我有一个元素与class ='myTestClass' - 如何应用css样式给这个元素的所有孩子。我只想把风格应用到元素的孩子。不是它的大孩子。
我可以使用.myTestClass> div {margin:0 20px; }
适用于所有的div儿童,但我想要一个适用于所有儿童的解决方案。我想我可以使用*,但
.myTestClass> * {margin:0 20px; }
无法使用。
已添加:
.myTestClass> *选择器不应用规则在firefox 26中,根据firebug没有其他规则。它的工作原理,如果我用div替换*)。
如 / p> 您需要在元素中扭曲 JSFiddle - DEMO 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. 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 .myTestClass > * { margin:0 20px; } does not work. Added: 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. You need to warp your JSFiddle - DEMO
这篇关于如何对元素的所有子元素应用样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
.myTestClass
,并通过添加 .wrapper *
后代选择器,然后添加 .myTestClass> *
子选择器将样式应用于元素children ,而不是它的大孩子。例如像这样:
.wrapper * {color:blue; margin:0 100px; / *仅用于演示* /}。myTestClass> * {color:red; margin:0 20px;}
< div class = wrapper> < div class =myTestClass>文字0< div>文字1< / div> < span>文字1< / span> < div>文字1< p>文字2< / p> < div>文字2< / div> < / div> < p>文字1< / p> < / div> < div>文字0< / div>< / div>
.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:.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>