How do I apply a style to all children of an element

MTilsted picture MTilsted · Oct 14, 2014 · Viewed 239.4k times · Source

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.

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.

Answer

Anonymous picture Anonymous · Oct 14, 2014

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 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 - 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>