Why does a style applied to a <td> override style applied to its parent <tr>?


I'm trying to style table with css by the use of :

tr:nth-child(odd) {background-color: black;}

td:nth-of-type(even) {background-color: green;}

But I'm asking why the td:nth-of-type(even) is stronger than the tr:nth-child(odd)? The cells, that must receive both styles are always green, why?

Problem courtesy of: clement


It's not a matter of "strength", it's because td is a sub-element of tr in the DOM tree and any style that overrides the parent is applied to the child elements:

According to the W3C HTML DOM standard, everything in an HTML document is a node:

The entire document is a document node Every HTML element is an element node The text inside HTML elements are text nodes Every HTML attribute is an attribute node Comments are comment nodes What this means is that if you supplied a style for it (which you did), then that style (or rule) will be evaluated and rendered.

For more info - look at this:


Solution courtesy of: jrd1


tr:nth-child(odd) {background-color: black;}

td:nth-of-type(even) {background-color: green;}

because in your CSS you have applied a style in td. which is the last rule. so basically what is in the last rule will override the previous rule as long as they conflict.

so if you want your style in tr to be followed. switch those lines. and then you may achieve what you want to do.

Discussion courtesy of: Johneric

1) Cells are green.

2) Rows are black.

In your example each row of green cells fully overlaps the black row.

I expect that assigning margins to <td> will show also the underlying black color.

Also try adding a "td" after the (odd) rule:

tr:nth-child(odd) td {background-color: black;}
Discussion courtesy of: Seavel

The td element is on top of the tr element. There is no specificity problem here, just stacking order. You'd see the same problem with any other nested elements:


<div class="a"><div class="b">Foo</div></div>

.a {
  background: black;

.b {
  background: green;
Discussion courtesy of: cimmanon

When I style, I think of it as the style closest to the thing I'm styling wins.

Let me attempt to redeem myself here. What I meant by the statement above is that I usually let me class selector drive most of my styling. On the rare cases where I want to override that inline, then since the inline style ALONG WITH the class selector takes specificity. Therefore, that inline element selector is "closer" to the thing I'm styling.

Also, when I'm writing my .css file, I keep in mind that the farther down the file it is, the "closer" it is to the thing I'm styling. I base this on statement 8 from the CSS Specificity: Things You Should Know article.

When selectors have an equal specificity value, the latest rule is the one that counts.

Discussion courtesy of: Nick DeVore

This recipe can be found in it's original form on Stack Over Flow.