I have a table inside a table, and I want to fill the background of the last row of table 1 only — not table 2.
<style> #test tr:last-child { background:#ff0000; } </style> <table border="1" width="100%" id="test"> <tr> <td> <table border="1" width="100%"> <tr> <td>table 2</td> </tr> </table> </td> </tr> <tr><td>table 1</td></tr> <tr><td>table 1</td></tr> <tr><td>table 1</td></tr> </table>
With my CSS, I'm coloring both last rows of table1 and table2.
In this CSS :last-child example, the last row (ie: the last <tr> tag) will have a yellow background color. All other rows in the table will not be styled by the :last-child selector.
The :nth-last-child(n) selector matches every element that is the nth child, regardless of type, of its parent, counting from the last child.
To affect just the second to the last LI delete the last CSS entry and set the second CSS entry's (n+3) content to empty ('').
Your tables should have as immediate children just tbody
and thead
elements, with the rows within*. So, amend the HTML to be:
<table border="1" width="100%" id="test"> <tbody> <tr> <td> <table border="1" width="100%"> <tbody> <tr> <td>table 2</td> </tr> </tbody> </table> </td> </tr> <tr><td>table 1</td></tr> <tr><td>table 1</td></tr> <tr><td>table 1</td></tr> </tbody> </table>
Then amend your selector slightly to this:
#test > tbody > tr:last-child { background:#ff0000; }
See it in action here. That makes use of the child selector, which:
...separates two selectors and matches only those elements matched by the second selector that are direct children of elements matched by the first.
So, you are targeting only direct children of tbody
elements that are themselves direct children of your #test
table.
The above is the neatest solution, as you don't need to over-ride any styles. The alternative would be to stick with your current set-up, and over-ride the background style for the inner table, like this:
#test tr:last-child { background:#ff0000; } #test table tr:last-child { background:transparent; }
* It's not mandatory but most (all?) browsers will add these in, so it's best to make it explicit. As @BoltClock states in the comments:
...it's now set in stone in HTML5, so for a browser to be compliant it basically must behave this way.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With