我可以组合:nth-​​child()或:nth-​​of-type()与任意选择器?

我可以组合:nth-child()或:nth-of-type()与任意选择器?

有没有办法选择匹配(或不匹配)任意选择器的每个第n个孩子?例如,我想选择每个奇数表行,但是在行的子集中:

table.myClass tr.row:nth-child(odd) {
  ...}
<table class="myClass">
  <tr>
    <td>Row  <tr class="row"> <!-- I want this -->
    <td>Row  <tr class="row">
    <td>Row  <tr class="row"> <!-- And this -->
    <td>Row</table>

:nth-child()似乎只计算所有tr元素,无论它们是否属于“行”类,所以我最终得到一个偶数“行”元素而不是我正在寻找的两个元素。同样的事情发生在:nth-of-type()

有人可以解释原因吗?


临摹微笑
浏览 703回答 5
5回答

MMTTMM

并不是的..引用文档的:nth-child伪类相匹配,其具有+ B-1的元素的兄弟姐妹之前它在文档树,对于一个给定的正或零值对于n,并且具有父元素。它是一个自己的选择器,不与类结合。在你的规则中,它必须同时满足两个选择器,因此:nth-child(even)如果它们碰巧有.row类,它将显示表行。

呼啦一阵风

您可以使用xpath执行此操作。//tr[contains(@class, 'row') and position() mod 2 = 0]可能有用的东西。还有其他SO问题扩展到如何更准确地匹配类的细节。

墨色风雨

这是你的答案<!DOCTYPE&nbsp;html><html&nbsp;lang="en"><head> &nbsp;&nbsp;<meta&nbsp;charset="UTF-8"> &nbsp;&nbsp;<meta&nbsp;name="viewport"&nbsp;content="width=device-width,&nbsp;initial-scale=1"> &nbsp;&nbsp;<title>TEST</title> &nbsp;&nbsp;<style> &nbsp;&nbsp;&nbsp;&nbsp;.block&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;background:&nbsp;#fc0; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;margin-bottom:&nbsp;10px; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;padding:&nbsp;10px; &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;/*&nbsp;.large&nbsp;>&nbsp;.large-item:nth-of-type(n+5)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;background:&nbsp;#f00; &nbsp;&nbsp;&nbsp;&nbsp;}&nbsp;*/ &nbsp;&nbsp;&nbsp;&nbsp;.large-item&nbsp;~&nbsp;.large-item&nbsp;~&nbsp;.large-item&nbsp;~&nbsp;.large-item&nbsp;~&nbsp;.large-item&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;background:&nbsp;#f00; &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;</style></head><body><h1>Should&nbsp;be&nbsp;the&nbsp;6th&nbsp;Hello&nbsp;Block&nbsp;that&nbsp;start&nbsp;red</h1><div&nbsp;class="small&nbsp;large"> &nbsp;&nbsp;<div&nbsp;class="block&nbsp;small-item">Hello&nbsp;block&nbsp;1</div> &nbsp;&nbsp;<div&nbsp;class="block&nbsp;small-item&nbsp;large-item">Hello&nbsp;block&nbsp;2</div> &nbsp;&nbsp;<div&nbsp;class="block&nbsp;small-item&nbsp;large-item">Hello&nbsp;block&nbsp;3</div> &nbsp;&nbsp;<div&nbsp;class="block&nbsp;small-item&nbsp;large-item">Hello&nbsp;block&nbsp;4</div> &nbsp;&nbsp;<div&nbsp;class="block&nbsp;small-item&nbsp;large-item">Hello&nbsp;block&nbsp;5</div> &nbsp;&nbsp;<div&nbsp;class="block&nbsp;small-item&nbsp;large-item">Hello&nbsp;block&nbsp;6</div> &nbsp;&nbsp;<div&nbsp;class="block&nbsp;small-item&nbsp;large-item">Hello&nbsp;block&nbsp;7</div> &nbsp;&nbsp;<div&nbsp;class="block&nbsp;small-item&nbsp;large-item">Hello&nbsp;block&nbsp;8</div></div></body></html>
打开App,查看更多内容
随时随地看视频慕课网APP