Martin Blore
Martin Blore

Reputation: 2195

CSS Child Selector Issue

Can anyone tell me how the "Heading" and "Heading 2" are being coloured red in the following example? http://jsfiddle.net/zxfNU/1/

HTML

<div id="root">
    <p>
        <p>Test 1</p>

        <h3>Heading</h3>

        <h3>Heading 2</h3>

    </p>
</div>

<h3>Heading 3</h3>

CSS

div#root > h3
{
    color: red;
}

Isn't the CSS only selecting a h3 element if it's under the div, when in fact it's under the p element?

Upvotes: 4

Views: 85

Answers (4)

F.P
F.P

Reputation: 17831

Take a look at the rendered HTML, e.g. in Firebug:

enter image description here

That's because you can't put a p inside another p

@Your edited fiddle:

Now the following HTML is rendered:

enter image description here

And, as you also changed your CSS to div > h3, it's still colored red.

Upvotes: 0

GajendraSinghParihar
GajendraSinghParihar

Reputation: 9131

This is because p tag inside a p tag is not a valid Html Use Inspect element you will find your html as

  <div id="root">
    <p>
        </p><p>Test 1</p>

        <h3>Heading</h3>

        <h3>Heading 2</h3>

    <p></p>
</div>

<h3>Heading 3</h3>

Upvotes: 0

RDX RaN
RDX RaN

Reputation: 305

Instead of <p> use <div>, because <p> inside <p> is not valid markup.

Upvotes: 5

Sotiris
Sotiris

Reputation: 40096

p inside p is not valid markup. So the result html is:

<div id="root">
    <p></p>
    <p>Test 1</p>
    <h3>Heading</h3>       
    <h3>Heading 2</h3>
    <p></p>
</div>

As you can see browser fixes the wrong markup to follow the specification.

Upvotes: 5

Related Questions