我有一个普通的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>
Run Code Online (Sandbox Code Playgroud)
我想将CSS样式应用于td特定列中的每个表格单元格().是否可以在不将class/ style属性应用于该列中的每个表格单元格且没有JavaScript的情况下执行此操作?
RoT*_*oRa 65
除了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. */
Run Code Online (Sandbox Code Playgroud)
Nel*_*son 59
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 */ }
Run Code Online (Sandbox Code Playgroud)
超级干净的代码
Den*_*gan 35
使用<col>标签并按照本指南设置样式.这样,您只需要向<col>元素添加类(或内联样式规范),而不是<td>在表中添加每个类.
注意事项:
<col>标签仅支持造型border,background,width和visibility(和它们的衍生物,如background-color).border声明没有工作,除非<table>有border-collapse: collapse;和行为是浏览器之间的不一致.visibility由于已知错误,声明在Chrome中无法正常运行.Sea*_*oyd 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;
}
Run Code Online (Sandbox Code Playgroud)