Style Sheets - Part 9 (Contextual Selectors)

To fix this problem, it is possible to supply contextual information about where a particular style should be applied. For example, we can specify that the EM element should only be modified when it appears inside a paragraph like this:
<STYLE type="text/css">
   P EM {color:red}
</STYLE>
Now, our previous example does what we want:

Italic Header

It is critical that you protect your Guinness!

Contextual information is hierarchical in nature and can be supplied for an arbitrary number of levels. For example, we could specify a set of rules like this:
<STYLE type="text/css">
   P EM {color:red}
   UL.outline {color:blue}
   UL.outline UL {color:green}
   UL.outline UL UL {color:orange}
</STYLE>
And now try them out with the following HTML code:
<UL CLASS=outline>
<LI> This is a first-level item. </LI>
<UL>
<LI> This is a second-level item. </LI>
<UL>
<LI> This is a third-level item. </LI>
</UL>
</UL>
</UL>
Here's what it looks like: It is critical to keep in mind that the rules only get applied if they exactly match the enclosing context. For example, the following HTML code
<UL>
<LI> This is a first-level item. </LI>
<UL>
<LI> This is a second-level item. </LI>
<UL>
<LI> This is a third-level item. </LI>
</UL>
</UL>
</UL>
is unaffected and produces this: Do you see why?

Next