如何更改 html 和 css 中表格列的背景颜色?

问题描述

How to Change the Background colour of a table-column in html and css? I know how to change row colour. But I just can't seem to do this.

解决方法

使用 :nth-child pseudo selector 或与 :first-child 一起使用(在第一列的特定情况下)

td:nth-child(1) {
  background: red;
}
<table>
  <tr><td>a</td><td>1</td></tr>
  <tr><td>b</td><td>2</td></tr>
</table>

在您的具体情况下,它也可以通过:

td:first-child {
   background: red;
}
,

您可以定位每行中的第一个单元格(td 元素)并将背景设置为红色:

* {
  margin: 0;
  padding: 0;
}
table {
  border-collapse: collapse;
}
table tr td:first-child {
  background-color: red;
}
<table>
  <tr><td>cell col1</td><td>cell col2</td></tr>
  <tr><td>cell col1</td><td>cell col2</td></tr>
  <tr><td>cell col1</td><td>cell col2</td></tr>
</table>