Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 898
Jonathan Wood Avatar asked Mar 02 '12 03:03

Jonathan Wood


People also ask

Can you have two CSS classes?

To specify multiple classes, separate the class names with a space, e.g. <span class="left important">. This allows you to combine several CSS classes for one HTML element.

Which CSS selector has the highest precedence?

Now we can say that the priority of the CSS property in an HTML document is applied top to bottom and left to right. Values defined as Important will have the highest priority. Inline CSS has a higher priority than embedded and external CSS.

What is the order of priority of CSS?

Inline CSS has a higher priority than embedded and external CSS. So final Order is: Value defined as Important > Inline >id nesting > id > class nesting > class > tag nesting > tag.

Which has more priority class or ID in CSS?

Class and ID selector example If more than one rule applies to an element and specifies the same property, then CSS gives priority to the rule that has the more specific selector. An ID selector is more specific than a class selector, which in turn is more specific than a tag selector.


2 Answers

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.

like image 161
Dagg Nabbit Avatar answered Sep 23 '22 05:09

Dagg Nabbit


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
like image 44
zzzzBov Avatar answered Sep 25 '22 05:09

zzzzBov