The first selector we saw, the HTML element selector, gives developers control
over the appearance of their web pages, but it is heavy handed. Its all or nothing,
every paragraph or none.
Class selectors give us control over how different kinds, or classes of elements
will appear.
Contextual selectors give use fine tuned control over the appearance of HTML
elements when they are associated with other HTML elements.
You may or may not use the emphasis or the strong emphasis tags (<EM> and <STRONG>), preferring the italic and bold tags instead. If you keep in mind the golden rule, separate style from content, you'll see that the former tags are to be preferred. So for this example, I'll talk about these logical rather than physical tags.
Usually, the STRONG tag makes text appear as bold text in a web page. Using a style sheet, you might override this, making STRONG text appear in a different color, a different font, or in any number of ways. Let's suppose we want to follow typographical conventions. We'd make STRONG text appear in bold. To do this using a HTML element selector, we'd add the following statement to our style sheet:
STRONG {font-weight: bold}
What if we want to use the STRONG tag in a heading, and our headings are already bold? With the above statement, the strong text will appear the same as the text around it. What we would like is to have STRONG text appear differently when it is in a heading. This is what contextual selectors let us do.
The contextual selector is simply a list of HTML element selectors, each separated by a space. For example, the STRONG text inside a heading selector would be created like this
H1 STRONG {text-decoration: underline}
This statement selects any STRONG element inside a Heading of level 1, and draws it underlined.
You can create contextual selectors of any depth, for instance P LI STRONG selects STRONG elements inside List items, inside paragraphs.
The contextual selector gives us much finer control over the appearance of
a page. You may not find yourself using it frequently, but it can be very valuable.
This selector can in fact be used with selectors other than HTML element selectors.
Returning to our question and answer example, we could create selectors for
lists inside question paragraphs, and lists inside answer paragraphs, to give
a distinct appearance to each type of list. Our two selectors would be as follows:
P.question LI
(list items inside paragraphs of class "question")
P.answer LI
(list items inside paragraphs of class "answer")
As we are about to see, there are a number of other types of selector, all of which can be used with contextual selectors.