【问题标题】:Assign styles to certain elements within a table with CSS [duplicate]使用CSS为表格中的某些元素分配样式[重复]
【发布时间】:2016-12-02 06:12:07
【问题描述】:

可能重复:
Apply style in a table to specific columns within the th and td

我有一个表,我需要能够为不同的列分配不同的样式,我需要:-

  1. 表头中的前两列(表头1和表头2被赋予text-align:left;然后表头中的所有剩余表头被赋予text-align:center;

  2. 与表格行类似,表格中所有行的前两个都被赋予 text-align:left;然后其余的 tds 给定 text-align:center;

所以基本上整个表格的前两列将被留下,然后剩下的被居中??

`

<tr>

<th>Header 1</th>
<th>Header 2</th>
<th>Header 3</th>
<th>Header 4</th>
<th>Header 5</th>
</tr>
<tr>
<td>row 1, cell 1</td>
<td>row 1, cell 2</td>
<td>row 1, cell 3</td>
<td>row 1, cell 4</td>
<td>row 1, cell 5</td>
</tr>
<tr>
<td>row 2, cell 1</td>
<td>row 2, cell 2</td>
<td>row 2, cell 3</td>
<td>row 2, cell 4</td>
<td>row 2, cell 5</td>

</tr>

【问题讨论】:

  • 你的last question 有什么区别?只是您添加了行要求?
  • 是的,当我尝试类似于行时无法正常工作,第一行一直显示第 th 的样式
  • 您可以复制我之前的答案,只需将 th 替换为 td。

标签: html css html-table


【解决方案1】:

假设你的表有一个类mytable

.mytable td, .mytable th {
    text-align: center;
}
.mytable td:first-child, .mytable td:nth-child(2) {
    text-align: left;
}
.mytable th:first-child, .mytable th:nth-child(2) {
    text-align: left;
}

这可以更简洁地写成:

.mytable td, .mytable th {
    text-align: center;
}
.mytable td:nth-child(-n+2) {
    text-align: left;
}
.mytable th:nth-child(-n+2) {
    text-align: left;
}

【讨论】:

    猜你喜欢
    • 2012-08-03
    • 2021-04-01
    • 1970-01-01
    • 2019-05-31
    • 1970-01-01
    • 2013-08-17
    • 1970-01-01
    • 2013-01-12
    • 2012-07-20
    相关资源
    最近更新 更多