What's the difference?
Specificity. The browser will apply ALL the styles that match. They are generally applied in order of specificity (from least to most). The higher the specificity of a CSS selector, the greater the likelihood its declarations are used over another CSS rule's declarations.
When calculating specificity the rules are essentially:
- Inline styling wins (1,0,0,0 points)
- For each ID apply 0,1,0,0 points
- For each class, pseudo-class or attribute selector apply 0,0,1,0 points
- For each element reference, apply 0,0,0,1 point
Total them up for your selector as if they were a number. 1020 trumps 0123.
In this demo you can see how the final applied style is taken from several declarations. The most specific rules override any less specific ones that came before it:
td {color:#ccc; font-size:20px;}
.me {color:red; background:cyan;}
td.me {color:blue; font-weight:bold;}
tr td.me {color:pink; border:1px solid #7799aa;}
table tr td.me {color:orange;}
<table>
<tr><td>1</td><td class="me">2</td></tr>
</table>
Which is preferable?
It depends on how targeted your styles are meant to be. Are you trying to style all <p>
s or just one? Is it a global font style or just for certain element? etc. For global styling use element references and pseudo selectors. When you have specific multiple instances use classnames. Where you have a one-off case use an ID (or a class). For example: You could style all your buttons with low specificity... button {background:grey;}
...and override it with additional specificity: button.warning {background:red;}
. Be no more specific than you must be! (You might need to override a style later.)
Further reading: