Hommer Smith
Hommer Smith

Reputation: 27852

Overwrite rules of h4 with a class selector

I have the following html:

<div class="main">
  <div class="container">
      <h4 class="test"> Test </h4>
  </div>
</div>​

And the following CSS:

.main .container h4 {
 color: red;   

}
.test {
 color: blue;   
}

Why would the class .test not overwrite the color rule? How can I accomplish this?

Thanks

Upvotes: 0

Views: 20500

Answers (1)

Andy
Andy

Reputation: 14575

This is a specificity issue.

Specificity is how important a certain selector is. In this case your first declaration uses two classes, and an element. This means only an inline style, #id or something with more classes can over write it.

If you want to affect the class test, we can use .main .container .test, this is 3 classes and will now over write it!

If two things have the same specificity, for example if you use .main .container h4 again, the one that comes last in the document will take precedence.

There is a way to over write regardless of your specificity or where it comes in the document, and that is by adding !important to a certain style, for example .test { color: blue !important; }. This is not recommended if you can use what is described above as this may cause future issues.

The spec can be found here

A selector's specificity is calculated as follows:

  • count 1 if the declaration is from is a 'style' attribute rather than a rule with a selector, 0 otherwise (= a) (In HTML, values of an element's "style" attribute are style sheet rules. These rules have no selectors, so a=1, b=0, c=0, and d=0.)
  • count the number of ID attributes in the selector (= b)
  • count the number of other attributes and pseudo-classes in the selector (= c)
  • count the number of element names and pseudo-elements in the selector (= d)
  • The specificity is based only on the form of the selector. In particular, a selector of the form "[id=p33]" is counted as an attribute selector (a=0, b=0, c=1, d=0), even if the id attribute is defined as an "ID" in the source document's DTD.

Concatenating the four numbers a-b-c-d (in a number system with a large base) gives the specificity.

Upvotes: 7

Related Questions