13

If I want to add styling to all p elements inside of a div, why should I use

div > p{

  *style here*

}

as opposed to just

div p{

  *style here*

}

furthermore, if I want to use a pseudo class, why would I then choose to use ">"

div > p:first-child{

  *style here*

}

instead of

 div p:first-child{

   *style here*

 }

Are there any benefits or drawbacks? what does that operator do?

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
kjh
  • 3,407
  • 8
  • 42
  • 79
  • If you [*read the specification*](http://www.w3.org/TR/CSS2/) you could find out all this stuff.. and ask a more refined/focused question, should any questions remain. –  Aug 10 '12 at 01:06
  • possible duplicate of [What does ">" mean in CSS rules?](http://stackoverflow.com/questions/3225891/what-does-mean-in-css-rules) – John Conde Aug 10 '12 at 03:27

3 Answers3

19

It's the direct child, not a recursive match.

CSS

div > p {

}

HTML

<div>
   <p>Match</p>
   <span>
      <p>No match</p>
   </span>
</div>

CSS

div p {

}

Markup

<div>
   <p>Match</p>
   <span>
      <p>Match</p>
   </span>
</div>
Gabe
  • 49,577
  • 28
  • 142
  • 181
  • [Child Combinator](http://www.w3.org/TR/css3-selectors/#child-combinators) (from the W3 CSS3 spec) – steveax Aug 10 '12 at 00:58
  • but isn't the > unnecessary if i have :first-child after the p in my stylesheet? – kjh Aug 10 '12 at 01:01
  • :first-child is for first child only. > is for all direct childes :) – Miljan Puzović Aug 10 '12 at 01:06
  • ahh took me a while to understand, direct child just means the p is not nested within another element inside the div. for some reason, "direct child" registered to me as "first child". thanks for this. – kjh Aug 10 '12 at 01:09
  • You really shouldn't wrap a `p` in a `span` though. The browser may do something unexpected with that. – steveax Aug 10 '12 at 01:12
  • @steveax it's meant to demonstrate the concept of the combinator, not block vs inline constraints. – Gabe Aug 10 '12 at 01:14
  • @Gabe yes, but since it's not valid, the browser may close that span tag before the p. – steveax Aug 10 '12 at 01:15
  • @steveax, Yes, I know. Thanks for reiterating it. Like I said it was a conceptual example. – Gabe Aug 10 '12 at 01:18
3

Because it means direct child.

Your second example would match the p in this example

<div>
  <header>
    <p>
    </p>
  </header>
</div>
Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
1

> and (space) are relationship selectors meaning "child" and "descendant" respectively. On top of the semantic differences others have pointed out, a child selector computes faster as it avoids redundant DOM tree traversal on non-matching elements.

Community
  • 1
  • 1
Oleg
  • 24,465
  • 8
  • 61
  • 91