Reputation: 67193
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
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:
The higher values will always override the lower ones. In the case of a tie, the last rule loaded wins.
Upvotes: 27
Reputation: 179046
I highly recommend reading the actual CSS specification on specificty.
There are four levels:
!important
(a)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
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
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