Home · Examples · Conditional Selectors

Conditional Selectors

You might be thinking "Conditional?–I thought CSS was static code." Well yes, true, it is static. But allow me to explain.

According to the W3C spec, CSS is supposed to obey laws of specificity. If one selector is more specific than another, it will get selected before the lesser specific ones. Or, if one rule has a higher precedence than another, it'll get selected instead of another with lower precedence (or importance). For example...

Lets say we wanted to have all of our <h1> elements to look bold, and be in the Verdana font, here is the CSS code we would use to do that:

h1 {
  font-family: Verdana;
  font-weight: bold;
}

BUT, what if <h1> is used inside the content area? (defined by <div id="content">) In that case, CSS will force that <h1> to be italic, and Arial, instead of bold/Verdana.

#content h1 {
  font-family: Arial;
  font-style: italic;
  font-weight: normal;
}

So now, every <h1> that is a child of the <div id="content"> container will be Arial/italic, and every <h1> that is outside of it will be Verdana/bold. The reason is because selecting #content h1 is more specific than just selecting all h1 elements.

This exact same method can be used to differentiate between any other HTML element.

What if both selectors are exactly the same?

#match { color: red; }

#match { color: blue; }

If two selectors conflict with one another, in that case, the latter one always wins. So in the above example, all text inside of the <div id="match"> container (#match) will be blue.

How can I give a lower-ranked selector the highest precedence above all others?

#match { color: red !important; }

#match { color: blue; }

Ordinarily in the above example text inside of #match would always be blue, but if you wish to give an out-ranked selector higher precedence, this can be done by inserting an !important rule.

Occasionally, you'll need a selector which is outranked by another, to have a higher precedence in the cascading order. So in the above example, the #match ID would be red instead of blue, because its specifically designated as having higher precedence.

So, since style sheets cascade into one another, being familiar with the cascading order is a good thing. It will save you a lot of extra time and confusion. Otherwise, you may find yourself saying "Why doesn't this work?" an awful lot. And if you email asking me, I will point you to this article. grin

Related URLs

Aug 22, 2007

Comments

This article hasn't been commented yet.

Write a comment

* = required field

:

:

:


7 + 9 =