Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS selector last row from main table

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.

like image 553
Roh-Land Avatar asked Apr 15 '13 08:04

Roh-Land


People also ask

How do you select the last row of a table in CSS?

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.

Which nth child () selector will target only the last list item?

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.

How do I select the second last child in CSS?

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 ('').


1 Answers

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.

Alternative solution

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.

like image 81
CherryFlavourPez Avatar answered Oct 04 '22 11:10

CherryFlavourPez