如何在css中将表中的不同列设置为不同的宽度?

it_*_*ure -1 html css

有一个表包含3列.现在我想设置第一列100px宽度,第二列200px和最后一列300px.
将所有td设置为具有哪个列的内容是一个尴尬.
有更明智的方法吗?

jac*_*ack 8

假设您的表具有标准标记,您可以使用nth-childnth-of-type定位每行中的特定单元格.nth-child如果您的表有更多列,您可以替换任何数字.

/* nth-child(1) = the first td in each tr */
td:nth-child(1) {
  width: 100px;
  background: #ddd;
  }

/* the second */
td:nth-child(2) {
  width: 200px;
  background: #ccc;
}

/* the third */
td:nth-child(3) {
  width: 300px;
  background: #bbb;
 }
Run Code Online (Sandbox Code Playgroud)
<table>
  <tbody>
    <tr>
      <td>1.1</td>
      <td>1.2</td>
      <td>1.3</td>
      </tr>
    <tr>
      <td>2.1</td>
      <td>2.2</td>
      <td>2.3</td>
     </tr>
    </tbody>
  </table>
Run Code Online (Sandbox Code Playgroud)


Ant*_*Ant 5

您可以使用 nth-child 在 CSS 中执行此操作:

#myTable tr td {
  border: 1px solid #000;
}

#myTable tr td:first-child {
  width: 100px;
}
#myTable tr td:nth-child(2) {
  width: 200px;
}
#myTable tr td:last-child {
  width: 300px;
}
Run Code Online (Sandbox Code Playgroud)
<table id="myTable">
<tr>
  <td>100px</td>
  <td>200px</td>
  <td>300px</td>
</tr>
</table>
Run Code Online (Sandbox Code Playgroud)

如果超过 3 列,您可以只指定 nth-child(x)..