Roh-Land
Roh-Land

Reputation: 491

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.

Upvotes: 46

Views: 148556

Answers (1)

CherryFlavourPez
CherryFlavourPez

Reputation: 7487

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.

Upvotes: 100

Related Questions