Jonathan Wood
Jonathan Wood

Reputation: 67193

Two CSS Classes: Which one Wins?

The markup below aligns SAMPLE TEXT to the left.

To me, it seems like it should be aligned to the right. The class that aligns to the right is declared after the one that aligns left. And the class that aligns to the right is even referenced last. So why does the class that aligns to the left win?

CSS

.table {
    width: 100%;
}
.table td {
    text-align: left;
}
.cell {
    text-align: right;
}

HTML

<table class="table">
    <tr>
        <td class="cell">
             SAMPLE TEXT
        </td>
    </tr>
</table>​

Please see my jsFiddle Example.

Upvotes: 18

Views: 5152

Answers (4)

Dagg Nabbit
Dagg Nabbit

Reputation: 76736

The .table td selector has a higher specificity. CSS specificity rules are kind of weird... IDs weigh more than class names, which weigh more than tag names.

The specificity rules, in a nutshell:

  • For each tag name, add 1.
  • For each class name, add 10.
  • For each ID, add 100.

The higher values will always override the lower ones. In the case of a tie, the last rule loaded wins.

Upvotes: 27

zzzzBov
zzzzBov

Reputation: 179046

I highly recommend reading the actual CSS specification on specificty.

There are four levels:

  1. inline-styles, !important (a)
  2. IDs (b)
  3. classes, pseudo-classes, attribute selectors (c)
  4. element, pseudo-elements (d)

For every selector, add one to it's respective letter category:

#foo.bar baz -> a=0, b=1, c=1, d=1
#fizz#buzz   -> a=0, b=2, c=0, d=0

a trumps b trumps c trumps d.

If there's a tie the second one wins:

#foo #bar baz
#fizz #buzz baz  <-- same specificity, this one wins

Upvotes: 6

Joseph
Joseph

Reputation: 119837

styles of text-align by .table td will win over the text-align applied by cell

.table td specificity is (1-1) :

(10 x 1 class selector) + (1 x 1 element selector)

.cell specificity is (1-0) :

(10 x 1 class selector)

for .cell to win, it has to have a specificity higher than the others. It can also be equal to others but it has to be declared after the others of the same level.

read more about inheritance and specificity

Upvotes: 3

Dan675
Dan675

Reputation: 1767

If you do

.table {
    width: 100%;
}
.table td {
    text-align: left;
    color: Yellow;
    background-color: Red;
}
td.cell {
    text-align: right;
}

it will right align http://jsfiddle.net/VTrEE/4/

Upvotes: 1

Related Questions