【发布时间】: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