以不同方式设置表格的第一个<td>列的样式

Sha*_*lin 62 css padding css-selectors

如果我有table两列,我如何指定一个padding或任何其他css,以便它只适用于<td>s 的第一列.另外我如何同样地设置第n列的样式?

RRi*_*esh 131

您可以使用第n个子选择器.

定位你可以使用的第n个元素:

td:nth-child(n) {  
  /* your stuff here */
}
Run Code Online (Sandbox Code Playgroud)

(n从1开始)

  • 建议td:这是第一个孩子,主要是因为它对旧的IE版本有更多的支持.如果浏览器支持不是问题,则nth-child是一个强大的选择器,可以开始使用. (17认同)
  • 并且`n`以1开头,而不是0. (13认同)
  • 是的,对于第一个元素,"first-child"更好.但是OP要求两个:) (5认同)

MS *_*him 10

:第n个孩子():第n的类型()伪类允许用户选择与一个式元件。

语法是:nth-child(an+b),您可以在其中用您选择的数字替换 a 和 b。

例如,:nth-child(3n+1) 选择第 1、4、7 等子节点。

td:nth-child(3n+1) {  
  /* your stuff here */
}
Run Code Online (Sandbox Code Playgroud)

:nth-of-type() 的工作原理相同,除了它只考虑给定类型的元素(在示例中)。


Fel*_*Als 9

如果您要支持IE7,更兼容的解决方案是:

/* only the cells with no cell before (aka the first one) */
td {
    padding-left: 20px;
}
/* only the cells with at least one cell before (aka all except the first one) */
td + td {
    padding-left: 0;
}
Run Code Online (Sandbox Code Playgroud)

也适用li; 一般兄弟选择器~可能更适合混合元素,如标题h1后跟段落和副标题,然后是其他段落.


tia*_*ang 5

这应该有帮助。它的 CSS3 :first-child 在这里你应该说tr你想要设计的表格的第一个。http://reference.sitepoint.com/css/pseudoclass-firstchild

  • 此外,如果您只想设置特定表的第一个 `tr` 的样式,您可以放置​​ `.tableclass tr:first-child` 或 `#tableid tr:first-child` (3认同)