0

When defining a CSS class for table cells, I would expect to say td.classname. However, I have seen sample code saying table td.classname and a couple of the answers to How to apply style classes to td classes? say table tr td.classname. All variants seem to produce the same results in Chrome.

What's the difference, and which is preferable?

rwallace
  • 26,045
  • 30
  • 102
  • 195
  • 2
    Read about CSS Specificity https://developer.mozilla.org/en-US/docs/Web/CSS/Specificity – Moob Oct 31 '19 at 17:55

2 Answers2

2

The CSS syntax table td.classname means any <td class="classname"> tag inside a <table>, and table tr td.classname means any <td class="classname"> tag within a <tr> within a <table>.

Since every table cell is normally inside a table row inside a table, they are nearly synonyms. If there’s any esoteric exception to that, it must not be relevant to that particular HTML document. This would, however, exclude a <th>—if you only use that classname for this one purpose, you might just as easily write .classname.

Davislor
  • 12,287
  • 2
  • 26
  • 36
2

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:

connexo
  • 41,035
  • 12
  • 60
  • 87
Moob
  • 13,593
  • 1
  • 29
  • 45