How to Select First and Last <td> in a Row with CSS ?
When working with HTML tables, It’s common to want to style different styles to different rows and cells such as adding a different background color or border. In this article, we will see how we can select the first and last <td> in a row with CSS. For this, we will be using 2 methods:
- Using the :first-child and :last-child pseudo-classes,
- Using the :first-of-type and :last-of-type pseudo-classes.
In CSS, the :first-child pseudo-class is used to select the first child element of a given parent element. It is compatible with all other CSS selectors. The :last-child selector allows you to target the last element directly within the element that contains it.
In CSS, the :first-of-type selector allows you to target the element’s first appearance within its container. The :last-of-type selector allows you to target the element’s last occurrence within its container.
Syntax:
tr td:first-child, tr td:last-child { ... } tr td:first-of-type, tr td:last-of-type { ... }
Example 1: In this example, we added some styling on <td> cell like font family to cursive, text color to white, and last we added background color green and crimson. green color for first and crimson color for last.
HTML
<!DOCTYPE html> < html lang = "en" > < head > < style > table { border-collapse: collapse; width: 50%; } td { padding: 20px; } tr:nth-child(even) { background-color: #f2f2f2; } tr td:first-child { font-family: cursive; color: white; background-color: green; } tr td:last-child { font-family: cursive; color: white; background-color: crimson; } </ style > </ head > < body > < table > < tr > < td >First Cell</ td > < td >Middle Cell</ td > < td >Last Cell</ td > </ tr > < tr > < td >First Cell</ td > < td >Middle Cell</ td > < td >Last Cell</ td > </ tr > < tr > < td >First Cell</ td > < td >Middle Cell</ td > < td >Last Cell</ td > </ tr > </ table > </ body > </ html > |
Output:
Example 2: This one is the same as the previous one but the difference is that in the previous example, we used the :first-child and :last-child pseudo-class but in this example, we use the :first-of-type and :last-of-type pseudo-class.
HTML
<!DOCTYPE html> < html lang = "en" > < head > < style > table { border-collapse: collapse; width: 50%; } td { padding: 20px; } tr:nth-child(even) { background-color: #f2f2f2; } tr td:first-of-type { font-family: cursive; color: white; background-color: green; } tr td:last-of-type { font-family: cursive; color: white; background-color: crimson; } </ style > </ head > < body > < table > < tr > < td >First Cell</ td > < td >Middle Cell</ td > < td >Last Cell</ td > </ tr > < tr > < td >First Cell</ td > < td >Middle Cell</ td > < td >Last Cell</ td > </ tr > < tr > < td >First Cell</ td > < td >Middle Cell</ td > < td >Last Cell</ td > </ tr > </ table > </ body > </ html > |
Output: