【问题标题】:Unexpected behaviour from :nth-of-type(n+1)来自 :nth-of-type(n+1) 的意外行为
【发布时间】:2016-07-08 00:17:41
【问题描述】:

我是 x-of-type 系列 CSS 伪类的狂热用户:

  • :first-of-type
  • :last-of-type
  • :nth-of-type
  • :nth-last-of-type

我通常非常擅长确保任何一系列相似元素(列表项等)完全按照我的意愿显示。

然而,在过去的一个小时里,我一直被困在如何通过单个样式声明实现以下结果:

  • 项目 1 有一个border-bottom
  • 项目 2 有一个border-bottom
  • 项目 3 有一个border-bottom
  • 第 4 项(最后一项)没有 border-bottom

我已经达到了我所需要的,使用:

.item {
border-bottom:6px solid rgb(227,227,227);
}

.item:last-of-type {
border-bottom:none;
}

但为了简洁起见,我仍然希望通过一个声明来实现相同的结果。

问题:

为什么不

.item:nth-of-type(n-1) {
    border-bottom:6px solid rgb(227,227,227);
    }

.item:nth-last-of-type(n+1) {
    border-bottom:6px solid rgb(227,227,227);
    }

工作?

是不是因为n 只是一个无限的数字列表,包括页面上目标元素数量之前和之后的数字?

如果是这样,我如何在一个声明中声明“除了最后一项之外的所有内容”

(提前道歉,如果它真的很明显而我没有注意到它......)


已添加...

这是我正在使用的 HTML:

<aside>
<img src="" title="" alt="" />
<span class="something-else">Blah</span>
<span class="item">Item Details</span>

<img src="" title="" alt="" />
<span class="something-else">Blah</span>
<span class="item">Item Details</span>

<img src="" title="" alt="" />
<span class="something-else">Blah</span>
<span class="item">Item Details</span>

<img src="" title="" alt="" />
<span class="something-else">Blah</span>
<span class="item">Item Details</span>
</aside>

【问题讨论】:

  • 类选择器具有误导性;您可能想用类型选择器添加或替换它,以明确您不会混淆 :*-of-type 与假设的 :*-of-class 选择器 - 或者更好的是,将其替换为 :*-child .
  • :nth-of-type 伪类选择元素,而不是元素的类,所以在它前面添加一个像 .item 这样的类就像添加一个过滤器,只有在您的目标类型具有该类。您应该发布您要定位的 HTML,以便我们看到您正在使用的内容。
  • 啊啊啊...所以您不能将x-of-type 应用于?这或许可以解释为什么我过去一个小时一直在摸不着头脑……

标签: css css-selectors pseudo-class


【解决方案1】:

是否因为n 只是一个无限的数字列表,包括页面上目标元素数量之前和之后的数字?

是的,这就是为什么:nth-of-type(n-1) 似乎匹配每个元素:n 计数无限次。因此,当n 为 1 加上该元素类型的子元素总数时,最后一个类型仍然匹配。换句话说,任何b 的表达式n-b(或b &lt;= 1n+b)等价于n(本身为n-0),这是一个保证匹配。

:nth-last-of-type(n+1) 很接近,但是没有做你想做的事情的原因是因为n 从零开始计数,所以当n 为零时,n+1 匹配最后一个类型。

如果是这样,我如何在一个声明中声明“除了最后一项之外的所有内容”

你有两种方法。您接近的一个是:nth-last-of-type(n+2)。另一个是更清晰的:not(:last-of-type)

【讨论】:

  • :nth-last-of-type(n+2) !当然。如果我想得更努力一点,我就会到达那里。这是完美的 - 简洁而优雅。非常感谢,BoltClock。
【解决方案2】:

试试这个选择器:

.item:not(:last-of-type) {
    border-bottom:6px solid rgb(227,227,227);
}

它选择所有具有item 类的元素,即:not :last-of-type

请注意,您可以将:not() 与任何单个选择器一起使用。

/* This is valid */
p:not(.classA):not(.classB):not(.classC) {
    /* ... */
}

/* This isn’t: */
p:not(.classA.classB.classC) {
    /* ... */
}

【讨论】:

  • 干得好,@J F - 非常感谢。在这种情况下,我会回避:not(就像在许多其他情况下一样)——但这并不是因为我有任何理性或任何合理的理由这样做。感谢您的出色回答。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-03-07
  • 2016-04-02
  • 2012-11-29
  • 2013-11-20
  • 1970-01-01
  • 1970-01-01
  • 2016-06-21
相关资源
最近更新 更多