How to Select the First and Last <td> in a Row with CSS
In this snippet, you can find out how to select and style individual columns of your table, particularly the first and last <td> in the table row. For that, you need to use the child selector pseudo-classes: :first-child and :last-child.
Let’s see how this is done. First, create HTML.
Create HTML
- Use a <table> element and set the width through the style attribute.
- Add a <th> element with the colspan attribute.
- Use two <tr> elements and place <td> elements inside.
<table>
<tr>
<th colspan="5">Month and Date</th>
</tr>
<tr>
<td>January</td>
<td>February</td>
<td>March</td>
<td>April</td>
<td>May</td>
</tr>
<tr>
<td>10.01.2020</td>
<td>03.02.2020</td>
<td>15.03.2020</td>
<td>16.04.2020</td>
<td>12.05.2020</td>
</tr>
</table>
Add CSS
- Set the border for the <table>, <th>, and <td> elements.
- Add color and font-weight to the :first-child and :last-child of the <td> inside the <tr> tag.
table,
th,
td {
border: 1px solid #666;
}
tr td:first-child,
tr td:last-child {
color: #359900;
font-weight: bold;
}
Now, let’s see the full code.
Example of selecting the first and last <td> in a row:
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<style>
table,
th,
td {
border: 1px solid #666;
}
tr td:first-child,
tr td:last-child {
color: #359900;
font-weight: bold;
}
</style>
</head>
<body>
<table>
<tr>
<th colspan="5">Month and Date</th>
</tr>
<tr>
<td>January</td>
<td>February</td>
<td>March</td>
<td>April</td>
<td>May</td>
</tr>
<tr>
<td>10.01.2020</td>
<td>03.02.2020</td>
<td>15.03.2020</td>
<td>16.04.2020</td>
<td>12.05.2020</td>
</tr>
</table>
</body>
</html>
Result
Month and Date | ||||
---|---|---|---|---|
January | February | March | April | May |
10.01.2020 | 03.02.2020 | 15.03.2020 | 16.04.2020 | 12.05.2020 |