如何在一行中选择第一个和最后一个 TD?

如何在一行中选择第一个和最后一个 TD

tr > td[0],
tr > td[-1] {
/* styles */
}
322445 次浏览

你可以使用 :first-child:last-child伪选择器:

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

这应该可以在所有主流浏览器上运行,但是 IE7在动态添加元素时会出现一些问题(而且在 IE6中无法运行)。

您可以使用以下代码片段:

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

使用以下伪类:

: first-child 意思是“选择此元素,如果它是其父元素的 第一个孩子”。

: last-child 意思是“选择此元素,如果它是其父元素的 最后一个孩子”。

只有元素节点(HTML 标记)受到影响,这些伪类忽略文本节点。

你可以使用 翻译: first-child翻译: last-child pseudo-selectors:

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

或者你可以用其他方式

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


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

这两种方法都很有效

如果该行在 td之前包含一些前导(或尾随) th标记,则应该使用 :first-of-type:last-of-type选择器。否则,如果第一个 td不是行的第一个元素,那么它就不会被选中。

这意味着:

td:first-of-type, td:last-of-type {
/* styles */
}

如果使用 sass (scss) ,可以使用以下代码片段:

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

你可以用

Table tr td: first-child { css here } 第一个孩子和

Table tr td: last-child { css here } 最后一个孩子。