Descendant selectors are an elegant way to apply styles to specific areas of your page while reducing the need to embed classes within elements. First introduced in CSS1 in 1996, descendant selectors (then called contextual selectors) match elements that are descendants of other elements in the document tree. Composed of two or more selectors separated by whitespace, descendant selectors apply styles to elements that are contained within other elements. For example: The above selector is a pattern that matches all Becomes this: Even better, adopt a uniform look for all unordered lists within divs and eliminate the class, like this: Essentially, descendant selectors utilize the existing structure of your XHTML document to selectively apply styles. Rather than hard coding classes within specific elements you use the relationships among elements to apply styles. Your code becomes more modular, using containers that style their contents selectively. This separation of presentation from structure keeps your code clean and your style sheets lean. You don't have to stop at one generation for descendant selectors. You can add more selectors to get more specific. For example: This selector uses the universal selector (*) to match all This selector targets list elements within an unordered list, within an unordered list. You can also target specific elements with child selectors (>), adjacent sibling selectors (+), and attribute selectors ([...]). We'll talk about these and other selectors in future tweaks. Descendant selectors can be combined with grouping and shorthand properties to create small yet powerful patterns. So pay attention to your ancestors, their wisdom can carry you a long way.div.nav ul {font-size:1.1em;}
ul
elements contained within divs with a class of .nav
. So this:.nav {font-size:1.1em;}
...
<div>
<ul>
<li class="nav">One</li>
<li class="nav">Two</li>
...
</ul>
</div>
div.nav ul {font-size:1.1em;}
...
<div class="nav">
<ul>
<li>One</li>
<li>Two</li>
...
</ul>
</div>
div ul {font-size:1.1em;}
...
<div>
<ul>
<li>One</li>
<li>Two</li>
...
</ul>
</div>
Grandchildren Selectors
div * p
p
aragraphs that are grandchildren or greater of div
elements. Another example:ul ul li
Combine Descendant Selectors with Grouping
Further Reading
By website optimization on 6 Feb 2004 PM