【问题标题】:css: all td only if table has thcss:所有 td 仅当 table 有 th
【发布时间】:2012-01-05 04:01:15
【问题描述】:

有一个有效的 css 规则(jquery 仅作为最后机会)允许定义表的所有 td 的样式,只有当有第 th 行时。

更具体

<table>
  <tr>
    <td>
      STYLE 1 HERE, my background color is white
    </td>
  </tr>
</table>

<table>
  <tr>
    <th>
      some text
    </th>
  </tr>
  <tr>
    <td>
      STYLE 2 HERE, my table has TH, my background color is red
    </td>
  </tr>
</table>

CSS:

th, td {
    background-color:#ffffff
       }

?????? {
         background-color:#ff0000
       }

有办法吗?

提前致谢, 西乔帕斯

【问题讨论】:

    标签: html css css-selectors


    【解决方案1】:

    在 css 中,你不能真正做到这一点。有+“相邻”选择,但这要求节点共享一个直接的共同父节点。如果你有一排混合的&lt;td&gt;&lt;/td&gt;&lt;th&gt;&lt;/th&gt;,那么他们就有资格参加这个。但是您的 th 和 td 单元格位于不同的行中,因此它们不共享一个共同的 &lt;tr&gt; 父级。

    所以:

    th + td {
       color: red
    }
    

    适用于

    <tr>
       <th>Look ma, I'm red!</th>
       <td>ooer, a header</td>
    </tr>
    

    因为他们共享同一个父&lt;tr&gt;,但是

    <tr>
       <th>Header</th>
    </tr>
    <tr>
       <td>Dang, not red</td>
    </tr>
    

    不会,因为 th/td 节点有两个不同的父节点。

    【讨论】:

      【解决方案2】:

      我认为你的代码有点错误,因为你的背景白色的第一个实例的 css 应该是

      tr,td {
           background-color:'ffffff;
      }
      

      如果我让您尝试做的是在其中包含 &lt;th&gt; 的表格中设置 &lt;td&gt; 标记的背景,那么通过纯 css 您无法按照您设想的方式执行此操作。

      但是,更好的方法是将一个类附加到您要设置样式的 td 标记上,如此 js fiddle 所示。

      http://jsfiddle.net/zYQ9h/

      【讨论】:

        【解决方案3】:

        恐怕你不能,因为我们需要“父”选择器,例如:

        tr < th ~ tr td { background-color: red; }
        

        这可以读作“找到任何包含 th 的 tr,并将红色背景应用到它的 tr td 兄弟姐妹”

        不幸的是,没有 &lt; 选择器之类的东西,所以恐怕你不得不抛出一些 jQuery:

        $("table:has(tr th)").find("tr td").css("background-color","red");
        

        jQuery 选择器中的has() 完全符合我们希望的&gt; css 选择器的功能。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-08-29
          • 2020-12-30
          • 2016-09-18
          • 2022-11-04
          • 2012-07-10
          • 2017-12-11
          相关资源
          最近更新 更多