sc1013
sc1013

Reputation: 1126

CSS descendant selector

For this kind of selector "p span" will select all descendant elements of p.

But how come the following code doesn't work?

p span { font-weight:bold;color:blue }

<p>
    <p>
        <span>TEXT 1</span>
    </p>
    <p>
        <span>TEXT 2</span>
    </p>
    <span>TEXT 3</span>
    <span>TEXT 4</span>
    <span>TEXT 5</span>
</p>

TEXT 3 - 5 are descendants of first-level element p. But how come they don't show up in bold and blue? (TEXT 1 - 2 do show up the correct style)

Upvotes: 0

Views: 151

Answers (2)

Hristo
Hristo

Reputation: 46557

From the spec - http://www.w3.org/TR/html401/struct/text.html#h-9.3.1

The <p> element represents a paragraph. It cannot contain block-level elements (including <p> itself).

Try converting the <p> elements to <div> elements.

p span { font-weight:bold;color:blue }

<div>
    <div>
        <span>TEXT 1</span>
    </div>
    <div>
        <span>TEXT 2</span>
    </div>
    <span>TEXT 3</span>
    <span>TEXT 4</span>
    <span>TEXT 5</span>
</div>

Upvotes: 0

Marc B
Marc B

Reputation: 360862

<p> are a special-case tag in HTML. You cannot embed paragraphs inside another paragraph, and opening two P tags implicitly closes the previous one. Your code is actually interpreted as:

<p></p>   <---closed by having opened the next <p>
<p><span>TEXT1</span></p>
<p><span>TEXT2</span></p>
<span>3</span>
etc...

So the 3,4,5 spans are actually NOT inside a <p> at all.

Upvotes: 11

Related Questions