我有一个普通的HTML表格:
<table>
<tr>
<td class="first-column-style">FAT</td>
<td>...</td>
</tr>
<tr>
<td class="first-column-style">FAT</td>
<td>...</td>
</tr>
</table>
我想将CSS样式应用于特定列中的每个表格单元格(td
)。是否可以在不将class
/ style
属性应用于该列中的每个表格单元格且没有JavaScript的情况下执行此操作?
答案 0 :(得分:64)
除了Sean Patrick Floyd的解决方案,您还可以将:first-child
与相邻的兄弟选择器+
结合使用(IE6也不支持):
td:first-child { /* first column */ }
td:first-child + td { /* second column */ }
td:first-child + td + td { /* third column */ }
/* etc. */
答案 1 :(得分:57)
2015回答,基于第一个孩子的答案,但更多的清洁工。
https://developer.mozilla.org/en-US/docs/Web/CSS/%3Anth-child
td:nth-child(1) { /* first column */ }
td:nth-child(2) { /* second column */ }
td:nth-child(3) { /* third column */ }
超级干净的代码
答案 2 :(得分:34)
使用<col>
标记并在this guide之后设置样式。这样,您只需要向<col>
元素添加一个类(或内联样式规范),而不是表中的每个<td>
。
<强>注意事项:强>
<col>
代码仅支持样式border
,background
,width
和visibility
(及其派生词,例如background-color
)。 border
声明无效,除非<table>
有border-collapse: collapse;
,且浏览器之间的行为不一致。visibility
声明在Chrome中无效。答案 3 :(得分:16)
对于第一列和最后一列,您可以使用:first-child
和:last-child
伪类:
/* make the first cell of every row bold */
tr td:FIRST-CHILD{
font-weight:bold;
}
/* make the last cell of every row italic */
tr td:LAST-CHILD{
font-style:italic;
}
答案 4 :(得分:2)
以下内容允许您在表级别设置列的样式,并且可以以更一般的方式用于前面的示例,因为您不必对应用于给定列索引的样式进行假设。样式表本身。
我同意&lt; col&gt;如果它符合您的需求,那么最好的方法,但风格的范围非常有限。
样本样式列1,2和&amp; 4,灰色文字样式。
<强> HTML 强>
<table class="example col1-readonly col2-readonly col4-readonly">
<强> CSS 强>
.example.col1-readonly tr td:nth-child(1),
.example.col2-readonly tr td:nth-child(2),
.example.col3-readonly tr td:nth-child(3),
.example.col4-readonly tr td:nth-child(4) {
color:#555;
}
答案 5 :(得分:0)
这是旧帖子。 但是我有同样的问题。 发现这是可行的:
<!DOCTYPE html>
<html>
<head>
<style>
tr:nth-child(3)>td:nth-child(2){background: red;}
</style>
</head>
<table>
<tr><td></td><td>A</td><td>B</td><td>C</td></tr>
<tr><td>1</td><td>A1</td><td>B1</td><td>C1</td></tr>
<tr><td>2</td><td>A2</td><td>B2</td><td>C2</td></tr>
<tr><td>3</td><td>A3</td><td>B3</td><td>C3</td></tr>
</table>
</html>
此样式设置将第三行和第二列的背景颜色设置为红色,