23

Just wondering when you use multiple classes on the one element such as class="foo bar" and those classes are setup as below:

.foo {
    margin-right: 10px;
}


.bar {
    margin-right: 0px;
}

Which class will have specificity? Will the margin be 10px or 0px?

GEOCHET
  • 21,119
  • 15
  • 74
  • 98
Brett
  • 19,449
  • 54
  • 157
  • 290

4 Answers4

34

It works based on precedence within the CSS. Therefore the item to occur most recently will override any previous styles.

CASE 1

.red  { background : red; }
.blue  { background : blue; }

class = 'red blue' would be blue in this instance.

CASE 2

.blue  { background : blue; }
.red  { background : red; } 

class = 'blue red' would be red in this instance.

Working Example

Rion Williams
  • 74,820
  • 37
  • 200
  • 327
  • Great thanks. I think I got it, but since you named your classes red and blue rather than foo and bar it's a little confusing which is which haha – Brett Dec 09 '11 at 21:00
  • Stellar Answer; Here is another fiddle forked from yours with another example http://jsfiddle.net/ccatto/KZdJK/107/ displaying CSS precedence order example – Catto Sep 02 '15 at 18:29
8

Also, if you wish to target the element who has only both classes, you can use this syntax:

<ul>
  <li class="foo first">Something</li>
  <li class="foo">Somthing else</li>
  <li class="foo">Something more</li>
</ul>

.foo {
  color: red;
}
.foo.first {
  color: blue
}
Joel Glovier
  • 7,469
  • 9
  • 51
  • 86
4

A single class name carries the same weight. In such a scenario, the rule that is listed first will be overwritten by the second, and hence, the element will have margin-right: 0px;

Here is a simple example using color instead of margin, because it's easier to visualize. The value specified in bar will be chosen by the browser.

wsanville
  • 37,158
  • 8
  • 76
  • 101
-2

In addition, more "specific" class will override a more generic one:

HTML:

<div class="foo">
    <div class="bar">Hello World!</div>
</div>

With the following CSS:

.foo .bar { margin-left:25px }
.bar { margin-left:0px }

Notice how the inner div still has 25px margin to the left?

Also, read up on "!important" argument after providing the value:

.bar { margin-left:0px!important }

Check out

MK_Dev
  • 3,291
  • 5
  • 27
  • 45
  • Yeah..... already knew about the specificity between more "specific" stuff, just wasn't sure about using two classes that weren't any more specific. – Brett Dec 09 '11 at 21:04
  • All classes are equally specific. It is the *combination* of two class selectors that makes `.foo .bar` more specific than `.bar` alone. – Jukka K. Korpela Oct 09 '12 at 13:50