HNikolas
HNikolas

Reputation: 413

Selecting children elements but NOT grandchildren

I have the following, simplified, code:

<div id="content">
    <p>text</p>

    <div id="container">
        <div id="col1">
            <p>text</p>
        </div>
        <div id="col2">
            <p>text</p>
        </div>
    </div>

    <p>text</p>
    </div>
</div>

Whenever I set some values to the #content p element in the CSS file, the changes also apply to the #col1 p and #col2 p.

What I would like to do is select only the children p elements of the #content div and not select the grandchildren p elements.

I imagine that one way of doing it would be to add a class to the first children and then apply properties throught it.

Is there any better way of doing it in either CSS2 or CSS3?

Upvotes: 26

Views: 22289

Answers (2)

Bas Slagter
Bas Slagter

Reputation: 9929

You can also set another style for the deeper <p> elements that override the one you already specified. Like so:

#content p { color: red; }
#content div p { color: black; }

Upvotes: 0

CD..
CD..

Reputation: 74096

Use the CSS Greater than sign > (Child selectors):

#content > p

A child selector matches when an element is the child of some element.

Upvotes: 54

Related Questions