CSS Pseudo-Class Selectors
Thanks to Eric Meyer author of Cascading
Style Sheets: The Definitive Guide for the following, in
which he patiently explains the way CSS pseudo-class selectors
work, particularly in conjunction with descendent (contextual)
selectors.
Let's say that I want a given style to be applied to the content
of all TD elements. That's written as:
TD {color: red;}
Right, no surprises there. In CSS terminology, the selector 'TD'
is
an element selector which matches all elements of that name. Now,
if I want to color only those TD elements which have a class of
'navbar' then I write:
TD.navbar {color: red;}
Again, the selector matches any 'TD' element with a class of 'navbar'.
Similarly, if I want a selector which matches (or "selects")
all unvisited hyperlinks, I write the following:
A:link {color: blue;}
So now I put the two together. I want to select any unvisited
hyperlink which is found within a TD element with a class of
'navbar'. In other words, I only want those hyperlinks which are
descendants of said TD. Thus:
TD.navbar A:link {color: blue;}
The class is still found on the TD element, but I'm actually
selecting the hyperlinks which appear in that context (thus the
old
term of "contextual selector"). Let's say I want to select
only those unvisited hyperlinks which have a class of 'external'.
Thus:
A.external:link {color: green;}
But if I only want to select those unvisited hyperlinks which
have a class of external but appear inside TD elements with a class
of
'navbar', then we get:
TD.navbar A.external:link {color: lime;}
So what's important is to make sure that you're selecting the
right
element for the job you're trying to do. Here's sort of a combined
stylesheet:
BODY {background: white; color: black;}
TD.navbar {background: black; color: white;}
A:link {color: blue; background: white;}
TD.navbar A:link {color: green; background: black;}
TD.navbar A.external:link {color: lime; background: black;}
When I set the backgrounds for the links, I'm really setting
backgrounds on those links, not on the TD or the BODY or anything
else.
- Eric Meyer |