1. Home
  2. Computing & Technology
  3. Web Design / HTML

More from About.com

Common Problems Using CSS Descendant Selectors

Descendant Selectors Can Have a Bigger Effect Than You Intended

By Jennifer Kyrnin, About.com

One of the first things that most designers forget about CSS descendant selectors is that they are flexible. When CSS defines a descendant, it doesn't care whether the tag in question is the direct child, the grandchild, or some great-great-great-descendant of the initial element. In each of the following examples, the span tag is a descendant of the p tag:

<p><span> </span></p>
<p><strong><span> </span></strong></p>
<p><strong><em><span> </span></em></strong></p>
<p><a href="#"><strong><em><span> </span></em></strong></a></p>

But who cares? I mean, does it really matter whether the descendant is a child or a great-grandchild of the first element? After all, if the span tag is inside the p tag, it's a descendant and you'll want to style it - even if the HTML goes:

<p><strong><span> </span></strong></p>

Where the Descendant is Can Make a Difference

One of the most common occurrences of descendants making a difference is in nested lists and tables. In many situations the Web designer comes up with the styles for a list, but forgets that the list can have lists inside of them. For example, this HTML:

<ol>
<li>An ordered list</li>
<li>With 3 elements</li>
<li>And one nested list inside it:
  <ul>
  <li>An unordered list</li>
  <li>With 2 bullet points</li>
  </ul></li>
</ol>

If you put a descendant selector on the li as a descendant of the ol tag - all the li tags inside that list will be styled that way, for example, this CSS:

ol li { list-style-type: decimal; }

This CSS forces the nested undordered list to become ordered. See for yourself

Use a Child Selector Instead

Instead of the descendant selector, use a CSS child selector. This tells the browser to only affect the descendants that are directly below the parent selector. With lists, this is typically what you want to style anyway.

A child selector is the same two element selectors, only instead of being separated by a space, you separate them with a greater-than sign (>):

ol > li { list-style=type: decimal; }

This puts the numbers where you want them, and not where you don't. See for yourself.

Descendant selectors can have these types of problems with other nested elements - such as tables. If you are using descendant selectors, try to think of a situation where the descendant element might be lower down in the document tree than you expect. If it can keep the same style, then you're fine, but if the style should change, then you'll need to find another selector.

  1. Home
  2. Computing & Technology
  3. Web Design / HTML
  4. CSS
  5. CSS Selectors
  6. Common Problems Using CSS Descendant Selectors - Nested Lists and CSS Descendant Selectors

©2008 About.com, a part of The New York Times Company.

All rights reserved.