How to select first and last TD in a row?

CssCss Selectors

Css Problem Overview


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

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

Css Solutions


Solution 1 - Css

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).

Solution 2 - Css

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.

Solution 3 - Css

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

Solution 4 - Css

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 */
}

Solution 5 - Css

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*/
   }
 }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionclarkkView Question on Stackoverflow
Solution 1 - CssJames AllardiceView Answer on Stackoverflow
Solution 2 - CssFrancescoView Answer on Stackoverflow
Solution 3 - CssAjay GuptaView Answer on Stackoverflow
Solution 4 - CssChristopher ChicheView Answer on Stackoverflow
Solution 5 - CssAlbazView Answer on Stackoverflow