Wednesday, December 18, 2013

CSS, difference between child selector and descendant selector



In CSS, what is difference between "li > a" and "li a"?
">" is the child selector, only for child level from parent, not grandchildren,
"" is the descendant selector, can be children, grandchildren and more.
Example 1
<foo> <!-- parent -->
  <bar> <!-- child of foo, descendant of foo -->
    <baz> <!-- descendant of foo -->
    </baz>
  </bar>
</foo>
Example 2
CSS
li a{ color: green; }
li>a{ color: red; }
 

HTML code 1
<ul>
  <li><span><a href='#'>HERE</a></span></li>
</ul>

 "HERE" will display as green due to that it is grandchild not child of li, CSS "li>a" will not apply.

HTML code2
<ul>
  <li><a href='#'>HERE</a></li>
</ul>
  "HERE" will display as red due to that it is both descendant and child of li, both CSS "li>a" and "li a" will  apply.

No comments:

Post a Comment