188

How can you select the first and the last TD in a row?

tr > td[0],
tr > td[-1] {
/* styles */
}

6 Answers 6

417

You could use the :first-child and :last-child pseudo-selectors:

tr td:first-child,
tr td:last-child {
    /* styles */
}

This should work in all major browsers, but IE7 has some problems when elements are added dynamically (and it won't work in IE6).

6
  • and what if you want to select the second og third child?
    – clarkk
    Commented Aug 29, 2011 at 10:22
  • 2
    and whats the difference between tr > td and tr td?
    – clarkk
    Commented Aug 29, 2011 at 10:23
  • The following rule sets the style of all P elements that are children of BODY: body > P { line-height: 1.3 } You can see at: w3.org/TR/CSS2/selector.html#child-selectors (same page posted by James)
    – Francesco
    Commented Aug 29, 2011 at 10:27
  • 5
    @clarkk - The > selects direct children only. Without it, all descendants (e.g. children of children) will be selected. To select the 2nd or 3rd child, look into the nth-child pseudo-selector. Commented Aug 29, 2011 at 14:54
  • @BoltClock I saw once your solution to this problem using + . something like tr td + td + .... +td but what if i dont know how many td's i have ?
    – Royi Namir
    Commented May 1, 2013 at 10:07
20

You can use the following snippet:

  tr td:first-child {text-decoration: underline;}
  tr td:last-child {color: red;}

Using the following pseudo classes:

:first-child means "select this element if it is the first child of its parent".

:last-child means "select this element if it is the last child of its parent".

Only element nodes (HTML tags) are affected, these pseudo-classes ignore text nodes.

19

You could use the :first-child and :last-child pseudo-selectors:

tr td:first-child{
    color:red;
}
tr td:last-child {
    color:green
}

Or you can use other way like

// To first child 
tr td:nth-child(1){
    color:red;
}

// To last child 
tr td:nth-last-child(1){
    color:green;
}

Both way are perfectly working

5

If you use sass(scss) you can use the following snippet:

tr > td{
   /* styles for all td*/
   &:first-child{
     /* styles for first */ 
   }
   &:last-child{
    /* styles for last*/
   }
 }
5

If the row contains some leading (or trailing) th tags before the td you should use the :first-of-type and the :last-of-type selectors. Otherwise the first td won't be selected if it's not the first element of the row.

This gives:

td:first-of-type, td:last-of-type {
    /* styles */
}
1
  • 2
    you saved my time i was using last-child which was not working but your solution worked perfectly Commented Feb 13, 2020 at 6:10
-1

You can use

table tr td:first-child { css here } for First Child and

table tr td:last-child { css here } for last Child.

Not the answer you're looking for? Browse other questions tagged or ask your own question.