CSS技巧:nth-​​of-type()

Roc*_*uby 4 css sass css-selectors

嗨,我正在寻找一些特别的东西,甚至不确定它是否可以使用纯CSS完成:

<div-1> 
  <div-x></div-x>
  <div-x></div-x>
  <div-x></div-x>
  <div-x></div-x>
<div-1> 
Run Code Online (Sandbox Code Playgroud)

我在scss尝试做的是

if <div-x> render count is even
  then only apply &:last-child{ something; } to div number len(<div-x>)-1
end
Run Code Online (Sandbox Code Playgroud)

EG: 如果div-x渲染为4,则将伪元素应用于3rd div-x else

我试过下面,但它适用于所有奇数元素

&:nth-of-type(odd) {
  border-bottom: none;
}
Run Code Online (Sandbox Code Playgroud)

任何提示/帮助将不胜感激!

Spo*_*oky 6

你可以使用:nth-last-of-type:

.wrapper div:nth-of-type(even) + div:nth-last-of-type(2) {
    background-color: #ADD8E6;
}

/* for when there are only two occurrences of this element type */
.wrapper div:nth-last-of-type(2):first-of-type {
    background-color: #ADD8E6;
}
Run Code Online (Sandbox Code Playgroud)

第一个选择器div只有在倒数第二个出现之前才会设置倒数第二个样式div.第二个选择器是第一个选择器div,它也是倒数第二个div(当只有两个divs时).我仅仅为了可读性而使用了两个声明.

看看这个演示.

但是,请确保对伪类的支持足以满足您的要求.此页面(2013)指出:

:nth-last-of-type在CSS选择器模块3中引入,这意味着旧版本的浏览器不支持它.但是,现代浏览器支持无可挑剔,新的伪选择器广泛用于生产环境.如果您需要较旧的浏览器支持,可以使用针对IE的polyfill,或者以非关键方式使用这些选择器,也可以使用渐进增强功能.

此 MDN页面指出以下浏览器在给定版本中具有"基本支持":

?????????????????????????????????????????????????????????????????
? Chrome ? Firefox (Gecko) ? Internet Explorer ? Opera ? Safari ?
?????????????????????????????????????????????????????????????????
?   4.0  ?   3.5 (1.9.1)   ?        9.0        ?  9.5  ?   3.2  ?
?????????????????????????????????????????????????????????????????
Run Code Online (Sandbox Code Playgroud)

对于移动浏览器:

???????????????????????????????????????????????????????????????????????????????
? Android ? Firefox Mobile (Gecko) ? IE Mobile ? Opera Mobile ? Safari Mobile ?
???????????????????????????????????????????????????????????????????????????????
?   2.1   ?       1.0 (1.9.1)      ?    9.0    ?     10.0     ?      3.2      ?
???????????????????????????????????????????????????????????????????????????????
Run Code Online (Sandbox Code Playgroud)