[css] CSS Child vs Descendant selectors

I am a bit confused between these 2 selectors.

Does the descendent selector:

div p

select all p within a div whether or not it's an immediate descedent? So if the p is inside another div it will still be selected?

Then the child selector:

div > p

Whats the difference? Does a child mean immediate child? Eg.

<div><p>

vs

<div><div><p>

will both be selected, or not?

This question is related to css css-selectors

The answer is


div p 

Selects all 'p' elements where the parent is a 'div' element

div > p

It means immediate children Selects all 'p' elements where the parent is a 'div' element


Bascailly, "a b" selects all b's inside a, while "a>b" selects b's what are only children to the a, it will not select b what is child of b what is child of a.

This example illustrates the difference:

div span{background:red}
div>span{background:green}

<div><span>abc</span><span>def<span>ghi</span></span></div>

Background color of abc and def will be green, but ghi will have red background color.

IMPORTANT: If you change order of the rules to:

div>span{background:green}
div span{background:red}

All letters will have red background, because descendant selector selects child's too.


div > p matches ps that have a div parent - <div><p> in your question

div p matches ps that have a div ancestor (parent, grandparent, great grandparent, etc.) - <div><p> and <div><div><p> in your question


Yes, you are correct. div p will match the following example, but div > p will not.

<div><table><tr><td><p> <!...

The first one is called descendant selector and the second one is called child selector.


CSS selection and applying style to a particular element can be done through traversing through the dom element [Example

Example

.a .b .c .d{
    background: #bdbdbd;
}
div>div>div>div:last-child{
    background: red;
}
<div class='a'>The first paragraph.
 <div class='b'>The second paragraph.
  <div class='c'>The third paragraph.
   <div class='d'>The fourth paragraph.</div>
   <div class='e'>The fourth paragraph.</div>
  </div>
 </div>
</div>

Be aware that the child selector is not supported in Internet Explorer 6. (If you use the selector in a jQuery/Prototype/YUI etc selector rather than in a style sheet it still works though)


In theory: Child => an immediate descendant of an ancestor (e.g. Joe and his father)

Descendant => any element that is descended from a particular ancestor (e.g. Joe and his great-great-grand-father)

In practice: try this HTML:

<div class="one">
  <span>Span 1.
    <span>Span 2.</span>
  </span>
</div>

<div class="two">
  <span>Span 1.
    <span>Span 2.</span>
  </span>
</div>

with this CSS:

span { color: red; } 
div.one span { color: blue; } 
div.two > span { color: green; }

http://jsfiddle.net/X343c/1/