Reputation: 114
I have this two styles in CSS, both in an external linked css file, and applied to the same table, with class myTable (it's a simplified version of a larger problem):
.myTable th
{
background-color: gray;
}
.myTable tr:nth-child(odd)
{
background-color: blue;
}
When I run the page, the header is gray, but why? What I want to know is why the first rule is overwriting the second. If I understood well specificity calculations (and obviously I didn't) the second rule is more specific (all calculators give me 0, 1, 2 in the second rule and 0, 1, 1 in the first one). Why then, the header is gray and not blue, if the second rule has more specificity???? Could someone help me understand this, please? Thank you very very much...
Upvotes: 0
Views: 54
Reputation: 1851
CSS specificity does not apply in your situation.
Your CSS targets two different elements; th
and tr
.
You have to think about this from a layer perspective.
Because th
's are contained in tr
's then the background-color
of the th
will be displayed above the background-color
of the tr
.
Take this code for example:
<tr style="background-color: gray">
<th>Heading One</th>
<th style="background-color: red">Heading Two</th>
<th>Heading Three</th>
</tr>
The first and third th
have a transparent background-color
, so the background-color
of the tr
shows through them. The second th
has a background-color
defined so it shows as expected.
You can take a look at this jsfiddle to see it in action.
Upvotes: 1
Reputation: 26160
Your first rule is not overwriting the second rule.
The reason is that your header is grey is because it contains th
elements, and you only specified background: grey
for the th
elements. (And a th
is not the same as a tr
).
If you want alternating column colors in your header also, then modify your code to address both the th
and the td
, like so:
.myTable th {
background-color: gray;
}
.myTable td:nth-child(odd),
.myTable th:nth-child(odd) {
background-color: blue;
}
Upvotes: 0
Reputation: 167172
You forgot th
or td
:
.myTable tr:nth-child(odd) th,
.myTable tr:nth-child(odd) td {
background-color: blue;
}
Because you are applying for th
in your first class, you need to use that here. The th
is inside the tr
, so whatever you put, th
will be in front showing the grey colour.
Upvotes: 3