views:

178

answers:

7

CSS Question: If two different selectors apply to an element, who wins?

I know this shouldn't happen, but I want to tweak a legacy application, and the CSS is getting in the middle.

A: 

Usually it goes in order from left to right. Also, it depends on the browser; for example IE6 would ignore any selectors that it doesn't understand. If you want to override any selectors, you can use the !important property: important

qwertypants
A: 

See the specificity order section of the specification (along with the rest of that chapter as !important rules and the order the rules appear in the stylesheet have an impact too).

David Dorward
+4  A: 

The gory details in the spec are actually reasonably readable. In summary:

  1. !important rules and inline style rules win most.

  2. Otherwise, normally the more specific wins. #id is a more specific selector than .classname is a more specific selector than tagname.

  3. Where rules are equally specific, the one declared last wins.

There is no particular reason why this ‘shouldn't happen’. It's normal to specify a broad-brush rule and then add a more specific rule to target one case; multiple same-property rules on a single element are not unusual or undesirable.

bobince
+2  A: 

It should happen! That's why it's called CASCADING style sheets. You can find an example of the priorities here

Manu
A: 

The priority between selectors is controlled by how specific they are. More specific selectors win over less specific.

If two selectors are equally specific, the later one wins over the first one.

There are three levels of specificity, id, class and element. So #elem wins over .elem as an id is more specific. .elem .cont wins over .elem as it has more selectors at the same level.

Read more under "What happens when conflicts occur?" at Selectutorial.

Guffa
A: 

Order in the CSS file only matters if the selectors share the same specificity.

For more on selector specificity: Andy Clarke penned Specificity Wars which is the best overview of how they work.

Paul Irish
A: 

CSS stands for Cascading Style Sheets. This means that rules apply to elements in a cascading way. It's perfectly normal that different selectors apply to an element. Thinks, for example, to the following:

<div class="wrapper">
  <div id="foo" class="bar" style="some rules">Test</div>
</div>

The following rules would affect to the "foo" element:

.wrapper {
  //some other rules
}

#foo {
  // some more rules
}

.bar {
  // some more rules
}

Rules for priorities can be found here:

http://www.w3.org/TR/CSS2/cascade.html#cascade

I always advise to use the Firefox "firebug" plugin. It will show you exactly which properties are evaluated for a specific element and why, emphasizing overrides during the cascade.

Roberto Aloi