Question

I am using twitter bootstrap (TB) and it seems like their CSS Rules are taking precedence when they shouldn't. I created this fiddle to show the problem:

http://jsfiddle.net/whoiskb/Za2TB/

HTML

<div class="teaser">
     <h1 class="teaserText">Text text text <label>Label</label> Text <label>Activities</label></h1>
</div>

CSS (plus an external link to twitter bootstrap)

div.teaser h1.teaserText {
     font-size: 100px;
     font-weight: 100;
     color: black;
     line-height: 90px;
     font-family: "Trebuchet MS", "Arial Black", "Impact", "Arial";
     text-transform: uppercase;
}

div.teaser h1.teaserText label {
     color: #FCCE00;
}​

From what I understand about the specificity rules, the rules defined for label in TB should only get a value of 1 since html selectors get a value of 1. My class should have a value of 23 since I have 3 html selectors and 2 class selectors which should get a value of 10 each. As you can see in the fiddle though the label selector in the TB css definition is taking precedence.

Could someone explain what I am missing here?

BTW, I know I can use the !important tag to resolve this, I am just trying to get a better understanding of CSS Specificity rules.

Was it helpful?

Solution

Specificity rules only apply if different Rules target the **same element (as for your color of the label), not if different elements are targeted (even if some styles of that element would be inherited).

You have one stylerule applied to labels, and that is the color, which gets applied correctly. All your other styles are applied to another element, so the TB styles targeting the label directly are preferred of course.

Some styles are inherited (like font-size and line-height in your example), but they are overridden as soon as there is a rule targeting your element directly. TB overrides your font-size and line-height with the following rule:

label, input, button, select, textarea {
  font-size: 14px;
  font-weight: normal;
  line-height: 20px;
}

You could fix this easily by declaring:

div.teaser h1.teaserText label {
     color: #FCCE00;
     font-size:inherit;
     line-height:inherit;
     /* and so on */
}​

OTHER TIPS

I'm not exactly clear on what you think the problem is, but taking a guess:

CSS specificity decides what happens when there are two or more rules for one CSS property for a given element.

So, given this HTML:

<label class="myLabel">Hello!</label>

And this CSS:

label {
    color: red;
    font-size: 24px;
}

.myLabel {
    color: blue;
}

The label will be blue, because .myLabel is a more specific selector than label.

However, the label will also have a font size of 24 pixels, because the .myLabel block doesn't include a rule setting the font-size property.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top