CSS Selectors

A selector is the part of the CSS that tells the browser what item that style should apply to.  It's the difference between this:

{color: blue;}

which means absolutely nothing, and this:

a {color: blue;}

which tells the browser that links should be blue.  This isn't a very practical example, but it's probably the most straightforward there is.  So let's get a little more complicated and work with an example that's actually useful.

<div id="DivNumber1">
  <a href="#">This is lnk 1</a>
</div>
<div id="DivNumber2">
  <a href="#">This is link 2</a>
</div>

This would give us a document breakdown like this:

  • div#DivNumber1
    • a
  • div#DivNumber2
    • a

So far so good.  Now imagine that you want the links in DivNumber1 to be red, and the links in DivNumber2 to be blue.  The solution is surprisingly simple:

div#DivNumber1 a {color: red;}
div#DivNumber2 a {color: blue;}

You can use the XHTML tree structure to apply styles to elements within elements by putting the parent (or grandparent, or great-grandparent) node selector before it.

Overriding Styles

Of course, there's gotta be a way for the browser to resolve conflicting styles too.  What happens when you have an object that fits the bill for multiple selectors?

The browser will apply selectors in order of specificity.  If two selectors are equally specific, the later will override the previous.  Let's use the above example to illustrate.  With the following style sheet:

a {text-style: italic; color: blue;}
div#DivNumber1 a {text-style: normal; color: red;}
div#DivNumber1 a {color: green;}
div#DivNumber2 a {color: yellow;}

What color will the links in DivNumber1 be?  What about DivNumber2? Let's walk through it:

DivNumber1: First, the links are made blue and italic across the entire page.  The next line makes them red and non-italic.  And then the line after that overrides the color from the line above and makes them green w/o italic.  We skip the 4th line because it doesn't apply to this link.  The links are green and not italic.

DivNumber2: First, the links are made blue and italic across the entire page.  We skip the next 2 lines because they don't apply.  And the last line changes the color to yellow (but the italic still applies).  The links are yellow and italic.