AfterWorkGuinness
AfterWorkGuinness

Reputation: 1850

CSS child selector applying to nested elements

I want to make the paragraph that is a direct child of the div foo have blue text and all other paragraphs have blue text, but the css I have written is apply that style to nested

tags inside the div too.

CSS:

p {
  color:red;
}

#foo > p{
 color: blue;
}

HTML

<html>
<head>
  <link type="test/css" rel="stylesheet" href="test.css"/>
</head>
<body>
  <div id="foo">
  <p>
      This is the first line.<br/>
      This is the second line
      <p>Nested Paragraph</p>
  </p>
  </div>
  <p>Paragraph in new div</p>
</body>
</html>

Output (Chrome)

This is the first line. (blue) This is the second line (blue)

Nested Paragraph (blue)

Paragraph in new div (red)

Upvotes: 1

Views: 437

Answers (2)

Oka
Oka

Reputation: 26375

<p> elements may only contain phrasing content.

<p> elements are considered flow content, and as such your markup is invalid and parsed poorly. You can not nest <p> elements.

Your CSS selectors would work with proper HTML.

Upvotes: 1

lmgonzalves
lmgonzalves

Reputation: 6588

A p element don't have another p element inside it. The browser behavior is put the nested p outside. Because of that all of your paragraphs are childrens of #foo element.

The following HTML:

<p>
    This is the first line.
    This is the second line
    <p>Nested Paragraph</p>
</p>

Causes this output:

<p>
    This is the first line.
    This is the second line
</p>
<p>Nested Paragraph</p>

Check the outputted HTML in the following fiddle and you can see what I'm saying: https://jsfiddle.net/lmgonzalves/ahse0jzg/

Upvotes: 1

Related Questions