CSS - 有表亲选择器吗?

时间:2022-11-20
本文介绍了CSS - 有表亲选择器吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有下表(JS Fiddle):

<table class="data-table">
<thead>
    <tr>
        <th scope="col">Method</th>
        <th scope="col">Price</th>
    </tr>
</thead>
<tbody>
    <tr>
        <td>Pickup*</td>
        <td>no charge</td>
    </tr>
    <tr>
        <td>Campus mail</td>
        <td>no charge</td>
    </tr>
</tbody>
<tfoot>
    <tr>
        <td colspan="2">* At 1st floor desk</td>
    </tr>
</tfoot>
</table>

TBODY 的行已使用 :nth-child(2n) 选择器进行了斑马条纹处理.但是 TFOOT 中行的背景没有获得这些样式,并且只要表在 TBODY 中有偶数行,就会破坏偶数/奇数条带.

The rows of the TBODY have been zebra striped using an :nth-child(2n) selector. But the background of the row in the TFOOT doesn't get those styles, and breaks the even/odd striping any time the table has an even number of rows in the TBODY.

我想选择带有 .data-table tbody tr:nth-child(2n):last-child + tr 之类的 TFOOT 行,但这不起作用.+ 选择器用于共享单个父元素的相邻兄弟元素.这里的两个TR不是兄弟姐妹,他们是堂兄弟.

I'd like to select the TFOOT row with something like .data-table tbody tr:nth-child(2n):last-child + tr, but that won't work. The + selector is for adjacent sibling elements that share a single parent element. The two TRs here aren't siblings, they're cousins.

可以使用 jQuery(类似于 $(".data-table tbody tr:nth-child(2n):last-child").parent().next().find("tr").css({"background-color": "blue"})).但如果有的话,我更喜欢 CSS 解决方案.

I could use jQuery (something like $(".data-table tbody tr:nth-child(2n):last-child").parent().next().find("tr").css({"background-color": "blue"})). But I'd prefer a CSS solution if there is one.

那么,有没有办法选择元素的表亲?

So, is there any way to select an element's cousin?

推荐答案

CSS 在 DOM 中工作(尽管选择器是向后处理的),因此您不能向上导航元素树,然后再向下导航到元素的表亲.您只能在同一级别的元素上操作(仅向前),或者向下.

CSS works down the DOM (although selectors are processed backwards), so you can't navigate up an element tree and then back down to reach an element's cousin. You can only either operate on the same level of elements (only going forward), or go down.

你必须使用你的 jQuery 解决方案.

You'll have to go with your jQuery solution.

这篇关于CSS - 有表亲选择器吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!

上一篇:如何组合多个 CSS 规则? 下一篇::not() 否定是否接受后代选择器?

相关文章

最新文章