【问题标题】:What is wrong with my CSS - selects more then it should?我的 CSS 有什么问题 - 选择比它应该的更多?
【发布时间】:2011-11-24 02:49:48
【问题描述】:
<div id="top">
  <table>
    <tbody>
      <tr>
        <td>Cell number one content...</td>
        <td>Cell number two content...</td>
      </tr>
    <tbody>
  </table>
</div>

大概,这个 CSS 应该选择整个第一个单元格蓝色和第二个红色:

  div#top table tbody tr:first-child {
      background-color:blue;
   }
   div#top table tbody tr + tr {
      background-color:red;
   }

相反,会发生以下情况:

【问题讨论】:

  • 您应该设置一个 JSFiddle,以便示例渲染实际上与您提供给我们的代码相关。据我所知,您的渲染与您的 CSS 一致。

标签: html css css-selectors


【解决方案1】:

不完全是。 :first-child 在您的情况下是指“TR,它是 TBODY 的第一个孩子”。它并不意味着“TR 的第一个子元素”(TD)。

因此,您将蓝色应用于表格行,而不是第一个恰好是 tr 子级的 td。

如果你只想要第一个 td,那么:

div#top .... tr td:first-child { background-color: blue; }

【讨论】:

  • A tr 是其父级的第一个子级,它可能是也可能不是 tbody(即使 HTML 保证它是 tbody,CSS 也不会)。我知道我知道,我是个混蛋:)
  • 因此是“在你的情况下”,但是是的,我知道你的意思。
【解决方案2】:

如果你想改变行颜色,你也可以使用 CSS3:

tr:nth-child(odd)    { background-color:#eee; }

tr:nth-child(even)    { background-color:#fff; }

【讨论】:

    【解决方案3】:

    如果您只想要第二个孩子,您需要使用nth-child(2)。你现在使用的,tr + tr 会影响tr 之后的每一个tr,或者是第一个之后的每一个tr

    【讨论】:

      【解决方案4】:

      第一列使用td:nth-child(1),第二列使用td:nth-child(2)

      div#top table tbody tr:nth-child(1) td:nth-child(1) {
            background-color:blue;
         }
         div#top table tbody tr:nth-child(1)  td:nth-child(2) {
            background-color:red;
         }
      

      【讨论】:

        【解决方案5】:

        您是否尝试过使用nth-child?:

        div#top table tbody tr:nth-child(2) { 
          background-color:red; 
        } 
        

        这是一个 jsFiddle:http://jsfiddle.net/HGdzx/

        【讨论】:

          猜你喜欢
          • 2021-11-20
          • 2016-11-20
          • 2014-04-12
          • 2020-01-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多