CSS 如何连续选择第一个和最后一个TD?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7228800/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 01:25:48  来源:igfitidea点击:

How to select first and last TD in a row?

csscss-selectors

提问by clarkk

How can you select the first and the last TDin a row?

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

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

回答by James Allardice

You could use the :first-childand :last-childpseudo-selectors:

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

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

这应该适用于所有主流浏览器,但 IE7 在动态添加元素时会出现一些问题(在 IE6 中不起作用)。

回答by Francesco

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-childmeans "select this element if it is the first childof its parent".

:first-child表示“如果该元素是其父元素的第一个子元素,则选择该元素”。

:last-childmeans "select this element if it is the last childof its parent".

:last-child表示“如果该元素是其父元素的最后一个子元素,则选择该元素”。

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

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

回答by Ajay Gupta

You could use the :first-childand :last-childpseudo-selectors:

您可以使用:first-child:last-childpseudo-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

两种方式都完美地工作

回答by Christopher Chiche

If the row contains some leading (or trailing) thtags before the tdyou should use the :first-of-typeand the :last-of-typeselectors. Otherwise the first tdwon't be selected if it's not the first element of the row.

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

This gives:

这给出:

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

回答by Elbaz

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

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

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