Jon
Jon

Reputation: 866

Stumped by simple CSS inheritance

I have what seems to be a pretty common CSS inheritance situation, but I don't understand why it isn't working as I thought it would.

Here is what the inheritance looks like as seen from the Chrome web debugger

Inherit

So I would expect my style for ".homeBox p" would override the style for "#mainContent p". And yet ...

Cancelled Style

The #mainContent p style overrides .homeBox p. What gives?

Upvotes: 0

Views: 117

Answers (4)

Evert
Evert

Reputation: 8541

specificity, as mentioned in the earlier answers, is correct. The simplest fix is to not use ids! if you have to, take that into account when writing your css for nested elements, eg:

#mainContent .homeBox p{font-size: 15px;}

Upvotes: 0

chemick
chemick

Reputation: 146

It's because the #mainContent holds greater specificity than your other selectors: it's determined to be the most specific description of that element, and is chosen above class.

The rules for selector dominance are fairly complex, demonstrated in the W3 doc: http://www.w3.org/TR/CSS2/cascade.html#specificity

Upvotes: 1

Curtis
Curtis

Reputation: 103348

ID styles override class styles.

For consistency purposes, I try to avoid using ID styles where possible.

Its also useful to avoid using these when you start working with server side scripting which can sometimes re-render an ID (like ASP.NET does for example).

Upvotes: 2

Supr
Supr

Reputation: 19022

The order is first determined by specificity, and an id is more specific than a class.

Upvotes: 1

Related Questions