css - 无论您有多少个元素,都选择最后一个使用第 n 个子元素之前的元素?

标签 css css-selectors

<分区>

好的,所以我正在阅读 http://css-tricks.com/how-nth-child-works/ (并环顾网络)关于 :nth-child 伪类,但我找不到与我遇到的问题相关的任何信息:

有没有办法选择,例如,不管你有多少元素,都选择最后一个之前的元素?

例如:我在导航栏中有一个水平链接列表,但无论该导航栏中有多少链接,我都需要选择最后一个之前的那个。

这有意义吗?可以使用 :nth-child 伪类来完成吗?...或者以任何其他方式来完成?

我已经为这个问题绞尽脑汁好几天了。

谢谢。

最佳答案

您可以使用 :nth-last-child(2) :

li:nth-last-child(2) {
  color: red;
}

li:nth-last-child(2) {
  color: red;
}
<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <li>5</li>
</ul>

关于 :nth-last-child:

The :nth-last-child(an+b) CSS pseudo-class matches an element that has an+b-1 siblings after it in the document tree, for a given positive or zero value for n, and has a parent element.

In effect, it functions the same as :nth-child except it selects items counting backwards from the end of element series, not the start.

关于css - 无论您有多少个元素,都选择最后一个使用第 n 个子元素之前的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39903983/

相关文章:

css - 为什么Chrome无法加载CSS?

javascript - 使用 AngularJS Bootstrap : ng-disabled is not noticable with btn-xs (or btn-sm)

css - 如何修复解析错误 [ :] in my css?

CSS3 :unchecked pseudo-class

css - 为什么这个 CSS 选择器不比另一个更具体?

css - 在 1-st 和 4-th 25% inline-block 之间需要空格

javascript - 带有内容的 Bootstrap 4 选项卡无法正确使用仪表板

javascript - 找到并选择正确的类(class)

CSS 选择器 : no <img> as child

jquery - 如何在内部节点数未知的多重递归结构中选择最后一层 li?