如何通过 CSS 样式化列中的每个表单元格?

我有一个普通的 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>

我想对特定列中的每个表单元格(td)应用 CSS 样式。有没有可能不对该列中的每个表单元格应用 class/style属性,而且不使用 JavaScript?

109920 次浏览

使用 <col>标记并在 这本指南之后设置它的样式。这样,您只需要向 <col>元素添加一个类(或内联样式规范) ,而不是表中的每个 <td>

警告:

  • 任何行或单元格样式都将取代列样式。
  • <col>标签只支持样式化 borderbackgroundwidthvisibility(及其衍生物,如 background-color)。
  • 除非 <table>具有 border-collapse: collapse;,否则 border声明不起作用,而且浏览器之间的行为是不一致的。
  • 由于 known bug,在 Chrome 中 visibility声明不能正常工作。

对于第一列和最后一列,您可以使用 :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;
}

参考文献:

除了 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. */

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 */ }

超级干净的代码

The following allows you to style columns at table level, and can be used in a more general way to the previous examples, as you don't have to make assumptions about the styles applied to a given column index within the style sheet itself.

我同意 < col> 方法是最好的,如果它符合您的需要,但是样式的范围是非常有限的。

示例样式列1、2和4具有灰色文本样式。

超文本标示语言

<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;
}

这是一个旧的职位。 但我也有同样的问题。 发现这个有用:

<!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>

This style setting sets the background color to red in the third row and second column,