当长度未知时,CSS nth-child 选择除最后一个元素之外的所有元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27994116/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
CSS nth-child select all but last element when length is unknown
提问by Daniel Bonnell
UPDATE: The fiddle link I posted has the working code now. :not(:last-child)
and :nth-last-child(n + 2)
both work perfectly.
更新:我发布的小提琴链接现在有工作代码。:not(:last-child)
并且:nth-last-child(n + 2)
两者都完美地工作。
I'm trying to use the nth-child
or nth-last-child
selector to select every li
in a ul
except for the last one. The catch is, the length of the list can vary from 1 to 5 elements. I haven't been able to find any documentation or examples of how to accomplish this.
我试图使用nth-child
或nth-last-child
选择器选择每li
一个ul
除了最后一个。问题是,列表的长度可以从 1 到 5 个元素不等。我一直无法找到有关如何完成此操作的任何文档或示例。
Here is the HTML for the ul
:
这是 的 HTML ul
:
<ul class="breadcrumbs">
<li>
<a href="/">Home</a>
</li>
<li>
<a href="/categories/1">Articles</a>
</li>
<li>
<a href="/categories/6">Specials</a>
</li>
<li class="current">
<a href="/categories/6/articles/21">Song Lyrics</a>
</li>
</ul>
Here is my current code:
这是我当前的代码:
ul > li:nth-last-child(-1n+4) > a:hover {
color: red;
}
This code still selects the last element in the list. I've also tried the code below, but that doesn't select anything. I tried a number of other combinations as well, but they either didn't work at all or selected the last element.
此代码仍选择列表中的最后一个元素。我也试过下面的代码,但没有选择任何东西。我也尝试了许多其他组合,但它们要么根本不起作用,要么选择了最后一个元素。
ul > li:nth-child(1):nth-last-child(2) > a:hover {
color: red;
}
回答by nickford
Use :not(:last-child)
to target all except the last.
使用:not(:last-child)
瞄准所有除了最后。
回答by Joseph Marikle
Use :nth-last-of-type
or :nth-last-child
使用:nth-last-of-type
或:nth-last-child
li:nth-last-of-type(n + 2) a {
color: red;
}
<ul class="breadcrumbs">
<li>
<a href="/">Home</a>
</li>
<li>
<a href="/categories/1">Articles</a>
</li>
<li>
<a href="/categories/6">Specials</a>
</li>
<li class="current">
<a href="/categories/6/articles/21">Song Lyrics</a>
</li>
</ul>
回答by eliteware
You can use this
你可以用这个
<ul class="breadcrumbs">
<li>
<a href="/">Home</a>
</li>
<li>
<a href="/categories/1">Articles</a>
</li>
<li>
<a href="/categories/6">Specials</a>
</li>
<li class="current">
<a href="/categories/6/articles/21">Song Lyrics</a>
</li>
</ul>
CSS
CSS
ul > li{
background:red;
}
ul > li:last-child{
background:black;
}
But if you absolutely need to change their style outside of the main li element use this
但是,如果您绝对需要在主要 li 元素之外更改其样式,请使用此
ul > li{
background:black;
}
ul > li:not:last-child{
background:red;
}