Michael Samuel
Michael Samuel

Reputation: 3920

why CSS direct child selector applies style to indirect children

I have the following html code:

<div id="test">
<span>
    test 
    <span>test</span>
</span>        
</div>  

And the following CSS code:

#test > span {
color: red;
}

Isn't the above code supposed to select only the direct child span of test div? So only the first 'test' word should be red but the second 'test' word inside the child span should not be selected. Or I'm getting it all wrong??

Upvotes: 5

Views: 1472

Answers (2)

William Petersen
William Petersen

Reputation: 1

Simply keep you style for the first span child element.

    #test > span {
    color: red; 
    }

And add a style for the second span child element.

    <div id="test">
    <span>test 
    <span style="color: black;">test</span>
    </span>        
    </div>

Or you can set a class for the span element like this.

    .red_color {
    color: red; 
    }

And add it to your span element.

    <div id="test">
    <span>test 
    <span class="red_color">test</span>
    </span>        
    </div>

Upvotes: -2

Quentin
Quentin

Reputation: 944147

All else being equal, the default style for the span will be:

span { color: inherit; }

So, while the rule color: red; won't apply to it directly, it will take its color from the parent element's color.

For comparison, see what happens if you explicitly say span { color: blue; }.

Upvotes: 12

Related Questions