-2

What is the difference between the selectors div.red > p and div.red p?

Please point to the key difference between these CSS selectors.

HTML

<div class="red"><p></p><div class="blue"><p></p></div>

Does the first selector select only the first <p> element?

Community
  • 1
  • 1
luxi
  • 317
  • 1
  • 4
  • 17
  • [Google "div > p vs div p"](https://www.google.nl/search?q=site:stackoverflow.com+div+%3E+p+vs+div+p) yields several results – Rob W Apr 14 '13 at 14:21

4 Answers4

4
div > p

This will select only p elements that are a child of div

div p

This will select all descendent (i.e. children, children's children etc) p elements of a div

See here for more info.

devdigital
  • 34,151
  • 9
  • 98
  • 120
1

The easiest way of explaining that is to just make a simple DEMO.

HTML

<div id="id">
    <p>First text</p>
    <div>
        <p>Second text</p>
    </div>
</div>

CSS

div#id > p { background: red; }
div#id p { color: green; }

Only the first text has red background, because > takes only p that is direct child of div#id. The second one is not matched because there is another div between div#id and p.

However, they both are green, because div#id p matches all p that are descendant to div#id, no matter how deep in the Document Object Model.

MarcinJuraszek
  • 124,003
  • 15
  • 196
  • 263
0

The first selector says "All p tags that are a direct child of div". The second says "All p tags inside of div, regardless of whether they are children, grandchildren" and so on.

Jamie Dixon
  • 53,019
  • 19
  • 125
  • 162
-1

Consider the following HTML:

<div>
    <p>1</p>
    <p>
        <p>2</p>
        <p>3</p>
    </p>
    <p>4</p>
</div>
<p>5</p>

div > p will only select direct descendants: 1, 4 and the one with the p elements nested in it.

div p will select all p tags within a div: 1 2 3 4.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
James Coyle
  • 9,922
  • 1
  • 40
  • 48