You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

table的nth-child选择器失效求助:偶数行未被正确选中

Fixing Alternating Table Row Background Color Issue

Hey there, let's get that table row styling sorted out for you! The problem you're seeing (coloring columns instead of rows) comes from two small mistakes in your CSS selector, plus a tiny HTML structure error. Let's break it down:

What Went Wrong

  1. Incorrect Selector Syntax: Your code uses tr :nth-child:{ background:#CCC } — first, there's an unnecessary space between tr and :nth-child, which turns it into a descendant selector. This means it's targeting child elements of <tr> (like <td>) instead of the <tr> itself. Second, :nth-child requires parentheses to specify the pattern (like even or odd), and you had an extra colon before the opening brace.
  2. HTML Structure Error: Looking at your table code, there's an extra empty <tr> tag right before the second <tr class="view"> — this will throw off the row numbering for :nth-child, so we'll need to remove that too.

The Fix

First, use the correct CSS selector to target even rows in the table body:

/* Target even-numbered rows inside the table body */
tbody tr:nth-child(even) {
  background-color: #CCC;
}
  • tbody tr:nth-child(even): This selects every even <tr> element that's a direct child of <tbody> — exactly what you want for alternating row colors.
  • We use <tbody> to exclude the header row (in <thead>) from the alternating style, since you already have a custom background for it.

Then, fix the extra <tr> in your HTML. Here's the corrected snippet for that section:

<tbody>
  <tr class="view">
    <!-- First row content -->
  </tr>
  <!-- Removed the extra empty <tr> here -->
  <tr class="view">
    <td class="lab">Marketing / Media Plan</td>
    <!-- Rest of the row content -->
  </tr>
  <!-- Remaining rows -->
</tbody>

Why This Works

  • No space between tr and :nth-child means we're targeting the <tr> element itself, not its children.
  • nth-child(even) picks every second row starting from the 2nd one (if you wanted odd rows, use nth-child(odd)).
  • Wrapping the selector in tbody ensures we don't accidentally style the header row.

If you want to apply this only to your specific table (in case you have other tables on the page), you can add the table class to the selector:

.fold-table tbody tr:nth-child(even) {
  background-color: #CCC;
}

That should give you the alternating row background colors you're aiming for!

内容的提问来源于stack exchange,提问作者Christopher B

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:04:32