CSS 为表格的第一列 <td> 设置不同的样式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15675097/
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
Style the first <td> column of a table differently
提问by Shalin
If I have a table
with two columns, how do I specify a padding
or any other css so that it is applied just for the first column of <td>
s. Also how do I style an n-thcolumn similarly?
如果我有table
两列,我如何指定 apadding
或任何其他 css 以便它仅应用于<td>
s的第一列。另外,我如何类似地设置第 n列的样式?
回答by RRikesh
You could use the n-th child selector.
您可以使用第n 个子选择器。
to target the nth element you could then use:
定位到您可以使用的第 n 个元素:
td:nth-child(n) {
/* your stuff here */
}
(where n
starts at 1)
(n
从 1 开始)
回答by FelipeAls
If you've to support IE7, a more compatible solution is:
如果您必须支持 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;
}
Also works fine with li
; general sibling selector ~
may be more suitable with mixed elements like a heading h1 followed by paragraphs AND a subheading and then again other paragraphs.
也适用于li
; 一般同级选择器~
可能更适合混合元素,例如标题 h1 后跟段落和副标题,然后是其他段落。
回答by MS Ibrahim
The :nth-child()and :nth-of-type()pseudo-classes allows you to select elements with a formula.
的:第n个孩子()和:第n的类型()伪类允许用户选择与一个式元件。
The syntax is :nth-child(an+b), where you replace a and b by numbers of your choice.
语法是:nth-child(an+b),您可以在其中用您选择的数字替换 a 和 b。
For instance, :nth-child(3n+1) selects the 1st, 4th, 7th etc. child.
例如,:nth-child(3n+1) 选择第 1、4、7 等子节点。
td:nth-child(3n+1) {
/* your stuff here */
}
:nth-of-type()works the same, except that it only considers element of the given type ( in the example).
:nth-of-type() 的工作原理相同,除了它只考虑给定类型的元素(在示例中)。
回答by tiantang
This should help. Its CSS3 :first-child where you should say that the first tr
of the table you would like to style. http://reference.sitepoint.com/css/pseudoclass-firstchild
这应该有帮助。它的 CSS3 :first-child 在这里你应该说tr
你想要设计的表格的第一个。http://reference.sitepoint.com/css/pseudoclass-firstchild
回答by Saptarshi Banerjee
To select the first column of a table you can use this syntax
要选择表的第一列,您可以使用此语法
tr td:nth-child(1n + 2){
padding-left: 10px;
}