New Perspectives On Web Design

(C. Jardin) #1
By Harry Roberts CHAPTER 1

then you will always want to keep your specificity as low as possible. Speci-
ficity, after all, is the reason we have !important.
IDs have a much higher specificity that any other type of selector (save
for inline styles). They are, in fact, infinitely more specific than classes. No
amount of chained classes will ever be as specific as just one ID.
This hike in specificity can have some pretty unexpected, and certainly
undesirable, side effects. Take for example:


#sidebar {
background-color: #09f;
}


#sidebar,
#sidebar a {
color: #fff;
}


.twitter-widget {
background-color: #fff;
}


.twitter-widget,
.twitter-widget a {
color: #09f;
}


Here we simply have a sidebar (#sidebar {}) which has a blue (#09f)
background and whose text and any links inside it are white. We also have
a reusable Twitter widget (.twitter {}) which has a white background and
whose text and links are blue, the inverse of the sidebar.
What do you suppose would happen if we were to put the Twitter
widget in the sidebar? Yep, its links would become white on the widget’s
white background. Certainly not what we wanted. This happened because
the #sidebar a {} selector is infinitely more specific than the .twitter a {}
selector, thus trumping it. This is where IDs can become a huge pain.

Free download pdf