如何解决以不同方式设计表格的奇数/偶数行
我有以下 HTML:
<table id="price-table">
<tr><th>Price</th><th>Value</th></tr>
<tr class="price-row">
<td>0</td>
<td>1</td>
</tr>
<tr><th>Price</th><th>Value</th></tr>
<tr class="price-row">
<td>1</td>
<td>2</td>
</tr>
</table>
我正在尝试使用以下内容为每个奇数行设置类价格行的样式:
#price-table tr.price-row:nth-child(odd) {
color: green;
}
每一个偶数行使用:
#price-table tr.price-row:nth-child(even) {
color: blue;
}
然而,只有偶数行被设置样式,奇数行被完全忽略。我不明白这是为什么?第一行的 id 不是 1 会被设置为奇数,第二行的 id 不是 2 会被设置为偶数吗?
我应该提一下,我确实希望这个表可以扩展,以便能够添加更多行并正确设置样式。
非常困惑,我不知道还能尝试什么,这看起来并不复杂,除非我犯了一个非常愚蠢的错误。
编辑完整的 HTML:
<table id="price-table">
<tr>
<th>Price</th>
<th>Value</th>
</tr>
<tr class="price-row">
<td>0</td>
<td>1</td>
</tr>
<tr>
<th>Price</th>
<th>Value</th>
</tr>
<tr class="price-row">
<td>1</td>
<td>2</td>
</tr>
<tr>
<th>Price</th>
<th>Value</th>
</tr>
<tr class="price-row">
<td>0</td>
<td>1</td>
</tr>
<tr>
<th>Price</th>
<th>Value</th>
</tr>
<tr class="price-row">
<td>1</td>
<td>2</td>
</tr>
</table>
解决方法
您需要删除tr
中的选择器,否则它只会选择具有该类的tr
,它们在您的HTML结构中始终是偶数
tr:nth-child(odd) {
background-color: green;
}
tr:nth-child(even) {
background-color: blue;
}
<table id="price-table">
<tr>
<th>Price</th>
<th>Value</th>
</tr>
<tr class="price-row">
<td>0</td>
<td>1</td>
</tr>
<tr>
<th>Price</th>
<th>Value</th>
</tr>
<tr class="price-row">
<td>1</td>
<td>2</td>
</tr>
</table>
更新(基于op评论)
感谢您的回复,但我的目标是不对包含“价格值”的行设置样式
然后使用同级选择器(+
和 ~
)
/* this will select every .price-row that has a TR as immediate previous sibling*/
tr+.price-row {
background-color: green;
}
/*this will select every .price-row after the other .price-row */
.price-row~.price-row {
background: blue
}
<table id="price-table">
<tr>
<th>Price</th>
<th>Value</th>
</tr>
<tr class="price-row">
<td>0</td>
<td>1</td>
</tr>
<tr>
<th>Price</th>
<th>Value</th>
</tr>
<tr class="price-row">
<td>1</td>
<td>2</td>
</tr>
</table>
UPDATE2(基于 op 评论)
感谢更新的答案。然而,这似乎只在第一个“价格行”行之后设置第一行的样式。之后没有其他具有“price-row”类的奇数行被设置为奇数,只有偶数?
您可以像下面那样使用 nth-child()
tr:nth-child(2n+2) {
background: red
}
tr:nth-child(4n+2) {
background: blue
}
<table id="price-table">
<tr>
<th>Price</th>
<th>Value</th>
</tr>
<tr class="price-row">
<td>0</td>
<td>1</td>
</tr>
<tr>
<th>Price</th>
<th>Value</th>
</tr>
<tr class="price-row">
<td>1</td>
<td>2</td>
</tr>
<tr>
<th>Price</th>
<th>Value</th>
</tr>
<tr class="price-row">
<td>0</td>
<td>1</td>
</tr>
<tr>
<th>Price</th>
<th>Value</th>
</tr>
<tr class="price-row">
<td>1</td>
<td>2</td>
</tr>
<tr>
<th>Price</th>
<th>Value</th>
</tr>
<tr class="price-row">
<td>1</td>
<td>2</td>
</tr>
<tr>
<th>Price</th>
<th>Value</th>
</tr>
<tr class="price-row">
<td>1</td>
<td>2</td>
</tr>
</table>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。