To select the last row of a table, you can use CSS :last-child
selector. The :last-child selector selects only the last child of its parent element.
So, if you use tr:last-child
, it will only select the last row of the table. Similarly, to select the last column of each row of the table, you can use td:last-child
selector.
Let’s say we have the following table in our HTML file and we want to highlight its last row:
<table border="1"> <tr> <th>First Name</th> <th>Last Name</th> <th>Age</th> </tr> <tr> <td>John</td> <td>Doe</td> <td>23</td> </tr> <tr> <td>James</td> <td>Bond</td> <td>26</td> </tr> <tr> <td>Nick</td> <td>Jonas</td> <td>25</td> </tr> <tr> <td>John</td> <td>Doe</td> <td>24</td> </tr> </table>
To select the last row of the above table, we can simply use tr:last-child
selector and apply any CSS styles to it.
This is how you can do it in your CSS file:
table{ border-collapse: collapse; width: 100%; } td,th{ padding: 10px; } /* Select only the last row */ tr:last-child{ background: lightpink; }
This is how our table will look like after applying the above styles:
Select the Last Row using the :nth-last-child() Selector
You can also select the last row of the table using the :nth-last-child(N)
selector. The :nth-last-child() selector selects the nth child of its parent but counting from the last.
So, if we want to select the last row of the table, we have to keep the value of N as 1 because it’s the first row of the table counting from the last:
table{ border-collapse: collapse; width: 100%; } td,th{ padding: 10px; } /* Select only the last row */ tr:nth-last-child(1){ background: lightpink; }
Thanks for reading.