To select the first row of a table, you can use the :first-child
selector. The :first-child selector selects only the first child of its parent element.
For eg, if you wan to select only the first row of the table, you have to use tr:first-child
. Similarly, if you want to select the first column of each row, you have to use td:first-child
. That’s it.
Let’s say we have the following table in our HTML:
<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>
This is how you can select its first row and apply a light grey background color to it:
table{ border-collapse: collapse; width: 100%; } td,th{ padding: 10px; } /* Select only the first row */ tr:first-child{ background: lightgrey; }
This is how the table will look like after applying the above styles:
Method 2: Using the :nth-child Selector
You can also use the :nth-child()
selector to target the first row of the table. The :nth-child() selector takes in an integer value which is the position of the child element inside its parent counting from the top.
So, to select the first row of the table, you have to pass an integer value 1 into the :nth-child()
selector.
This is how you can do it:
/* Select only the first row */ tr:nth-child(1){ background: lightgrey; }
Thanks for reading.