: nth-of-type selector overrides all other CSS selectors

I am trying to review my HTML, JavaScript, and CSS3 exam; and I'm a little confused about CSS selectors and which take precedence.

I have the following CSS:

table                   { border: 1px solid black; }
tr:nth-child(odd)       { background-color: red; }
tr td:nth-of-type(even) { background-color: blue; }
td                      { background-color: green; }

I thought that everything that comes last takes precedence, therefore, in my opinion, all cells in the table will be green.

However, even cells are still blue, as is the nth-of-type selector. Even when I put this at the top and delete the green td line, the blue color is still displayed in the middle, and only the odd cells are displayed in red.

Can someone explain why nth-of-type seems to take precedence over everything else?

Here is an example:

table { border: 1px solid black; }
tr:nth-child(odd) { background-color: red; }
tr td:nth-of-type(even) { background-color: blue; }
td { background-color: green; }
<table style="width: 100%;">
  <tr>
    <td>Jill</td>
    <td>Smith</td>
    <td>50</td>
  </tr>
  <tr>
    <td>Eve</td>
    <td>Jackson</td>
    <td>94</td>
  </tr>
  <tr>
    <td>John</td>
    <td>Doe</td>
    <td>80</td>
  </tr>
  <tr>
    <td>John</td>
    <td>Doe</td>
    <td>80</td>
  </tr>
</table>
Run codeHide result

https://jsfiddle.net/e6157xwz/

+4
source share
4

, ?

.

:

  • (, *)
  • (, h1)
    (, .example)
    (, [type="radio"])
  • - (, :hover)
  • ID (, #example)
  • (, style="font-weight:bold")

:nth-of-type(even/odd) 3, , - type selectors ( 2.1).

MDN-, , , , .

+3

, . - , - , , .

, . , ( ) .

+2

- specificity . , td. :

tr td:nth-of-type(even) -> 0,0,1,2
td                      -> 0,0,0,1

.

+2

All Articles