nth-of-type(2) 是针对第一个类型?

nth-of-type(2) is targeting the first of type?

我有一个相对模块化的页面,但由于 CMS,其中一些段落块的内容不会填满整个块,所以我只想增加一些块的字体大小。但是,当我尝试定位 2 和 3 时,它似乎根本无法识别它。事实上,它只针对 第一个,在我的检查器中,它说它是因为它正在应用 2.

的规则

示例HTML

<div class="container">
    <div class="item video">
        <!-- HTML for video stuffs-->
    </div>
    <div class="item copy">
        <h1>Example Title</h1>
        <p>Example words</p>
    </div>
    <div class="item photo">
        <!-- HTML for photo stuffs-->
    </div>
    <div class="item video">
        <!-- HTML for video stuffs-->
    </div>
    <div class="item copy">
        <h1>Example Title</h1>
        <p>Example words</p>
    </div>
    <div class="item photo">
        <!-- HTML for photo stuffs-->
    </div>
    <div class="item video">
        <!-- HTML for video stuffs-->
    </div>
    <div class="item copy">
        <h1>Example Title</h1>
        <p>Example words</p>
    </div>
    <div class="item photo">
        <!-- HTML for photo stuffs-->
    </div>
    <div class="item video">
        <!-- HTML for video stuffs-->
    </div>
    <div class="item copy">
        <h1>Example Title</h1>
        <p>Example words</p>
    </div>
    <div class="item photo">
        <!-- HTML for photo stuffs-->
    </div>
</div>

现在我的 LESS 文件看起来像这样:

.container {
    .item {
        &.copy {
            p {
                font-size: 16px;
            }
            &:nth-of-type(2), &:nth-of-type(3) {
                p {
                    font-size: 17px;
                }
            }
        }
    }
}

理论上,第一个和第四个 .copy 块中的段落文本的字体大小应为 16px,而第二个和第三个块应为 17px。但是,我看到的是它们都是 16px,第一个是 17px,它突出显示说这是因为“.container .item.copy:nth-of-type(2) p 的规则" 正在覆盖它。

为什么第 nth-of-type(2) 规则针对其类型的第一个块而不是第二个块?为什么 nth-of-type(3) 规则不针对它的类型的第二个块,如果它是这样计算它们的?我对这里发生的事情感到很困惑......非常感谢任何帮助。

所以我看了this answer, but I didn't quite understand it until I read this one

"nth-of-type" 规则不适用于 类;它只查看元素的类型。所以我的第一个 .copy 块被 nth-of-type(2) 规则作为目标的原因是因为它是第二个 div.

太糟糕了,类 没有简单的等价物。如果有请告诉我!

谢谢大家!

编辑: 至于解决方案,我只是针对 &:nth-child(5), &:nth-child(8)。由于它们在该级别上都是 div,因此不需要 nth-of-type。幸运的是,这个页面的布局是硬编码的,所以这些索引不会很快改变。如果是,我可能会通过 JavaScript 定位他们并应用 类 或其他东西。

这是一个有用的作弊 sheet,适用于 W3schools 的所有 CSS 选择器(您可以使用它):Try CSS selector

这是一个引出答案的简短示例:

li:nth-of-type(2) means:
All <li> elements that are the second <li> element of their parent.

:nth-of-type 在给定 class selected (".item.copy" 的 type 的元素中查找).该元素是 div,因此 css 规则应用于 html 结构级别的 div。

解决方案是使用 :nth-child,它在 html 结构级别中寻找具有给定 class (".item.copy") 的所有元素。它可以用于 select 几乎所有重复的模式。那是因为你可以这样写:

.item:nth-child(2n - 1) {} // This targets 1st, 3rd, 5th, 7th,...

注意 HTML 结构中的级别。当 li 元素中嵌套了 links(li 中总是一个 link)时,有一个常见的错误,然后当你想以每秒 link 为目标时,你必须这样写这个:

ul li:nth-child(2n) {
    a {
        //style the link
    }
}

对于使用第 nth-child selector,有一个非常有用的功能: https://css-tricks.com/examples/nth-child-tester/