Kyl*_*ppd 41 css css-selectors
我有一个无序列表,可以包含偶数或奇数的项目.我正在寻找一种仅限CSS的方法,li如果lis 的数量是偶数,则从最后2个标签中删除边界.在:last-child不考虑伪选择删除最后一个.
li {
float: left;
border-bottom: 1px solid #000;
}
li:last-child{
border-bottom: none;
}
Run Code Online (Sandbox Code Playgroud)
lis+============================================+
+ 1 | 2 +
+--------------------------------------------+
+ 3 | +
+============================================+
Run Code Online (Sandbox Code Playgroud)
+============================================+
+ 1 | 2 +
+--------------------------------------------+
+ 3 | 4 +
+--------------------- +
+============================================+
Run Code Online (Sandbox Code Playgroud)
所以我想我可以使用,li:nth-last-child()但我无法弄清楚应该是什么应该是抓住最后一个奇怪的孩子.
这不2n+1,2n-1,n-1,或任何我能想到的.请帮忙.
Ben*_*ull 80
nth-last-child从最后一个孩子向后计数,所以要抓住倒数第二个,表达式是:
li:nth-last-child(2)
Run Code Online (Sandbox Code Playgroud)
你可以组合伪选择器,所以要选择倒数第二个孩子,但只有当它是奇数时,使用:
li:nth-last-child(2):nth-child(odd) {border-bottom: none;}
Run Code Online (Sandbox Code Playgroud)
所以,整个事情应该是:
li:last-child,
li:nth-last-child(2):nth-child(odd) {border-bottom: none;}
Run Code Online (Sandbox Code Playgroud)
回答@ ithil的问题,这是我在SASS中写的方式:
li
&:last-child,
&:nth-last-child(2):nth-child(odd)
border-bottom: none
Run Code Online (Sandbox Code Playgroud)
它并没有那么简单,因为选择'倒数第二个奇怪的孩子'总是需要'两步'选择器.
在回答@ Caspert的问题,你可以通过分组更多选择的任意许多过去的元素做到这一点(有感觉应该有一定的xn+y模式来做到这一点不进行分组,但AFAIU这些模式只是从最后一个元素,倒数工作).
最后三个要素:
li:last-child,
li:nth-last-child(2):nth-child(odd),
li:nth-last-child(3):nth-child(odd) {border-bottom: none;}
Run Code Online (Sandbox Code Playgroud)
这是一个像SASS这样的地方可以帮助你的地方,为你生成选择器.我会将其构造为占位符类,并使用它扩展元素,并在变量中设置列数,如下所示:
$number-of-columns: 3
%no-border-on-last-row
@for $i from 1 through $number-of-columns
&:nth-last-child($i):nth-child(odd)
border-bottom: none
//Then, to use it in your layout, just extend:
.column-grid-list li
@extend %no-border-on-last-row
Run Code Online (Sandbox Code Playgroud)
And*_*dri 10
另一种选择:
li:last-child:not(:nth-child(odd))
Run Code Online (Sandbox Code Playgroud)
这是一个小提琴:http://jsfiddle.net/W72nR/