SpaceNinja
SpaceNinja

Reputation: 512

Can CSS be used to style an element based on it's order in the DOM?

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

Answers (3)

FelipeAls
FelipeAls

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.
  • This is a wonderful trick for replacing :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.
  • The + 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.
  • The above code works whether there's a 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

wzub
wzub

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

BoltClock
BoltClock

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

Related Questions