Reputation: 512
I need to put a style on an element, but the element does not have a class or id, nor can I edit that portion of the code to put a class or id on it.
In jQuery, I would select it with .eq[4] or something, but I can only use CSS.
So the question is - can I style the second <td> in the second <tr>?
<table class="tableClass">
<tr>
<td>...</td>
<td>...</td>
<td>...</td>
</tr>
<tr>
<td>...</td>
<td> I NEED TO STYLE THIS ONE </td>
<td>...</td>
</tr>
</table>
Upvotes: 2
Views: 139
Reputation: 22171
Here's an alternate method that also works in IE7 and IE8 for better compatibility:
.tableClass tr + tr > td + td {
/* selects 2nd to last td from 2nd to last rows.
Do something here with some CSS instructions of your choice.
Beware of thead and th, they aren't expected in your example */
}
.tableClass tr + tr > td + td + td,
.tableClass tr + tr + tr > td + td {
/* selects 3rd to last td from 2nd to last rows and also
2nd to last td from 3rd to last rows.
Cancel here everything you did in previous CSS rule! */
}
td + td
selects everything except the first td
and td + td + td
selects everything except the first and second td
: with 2 CSS rules you're done. There's added complexity in your example because you also need to consider rows, but you just have to combine the latter selector rule with tr + tr + tr
selector. :not(:first-child)
and it's worth knowing about it; it's up to you to use it or not when it gets more complicated like in your example.+
can be replaced by a ~
(general sibling) when you're dealing with different elements like a h3 followed by p then h4 then again p. There'd be no p + p
here but there'd still be a p ~ p
.tbody
element between table
and tr
or not, as it doesn't expect each tr
to be a child of table
, only a descendant.Upvotes: 1
Reputation: 324
Sure, use the nth-child
selector. In this case,
table tr:nth-child(2) td:nth-child(2)
Here's a great explanation of how this works.
Upvotes: 1
Reputation: 723668
You can use :nth-child()
, but you need to use it with both the td
and its parent tr
:
.tableClass > tr:nth-child(2) > td:nth-child(2)
Upvotes: 3