你可以使用: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;
}
第一个选择器将设置倒数第二个选择器的样式div
仅当它紧接在偶数事件之前div
。第二个选择器是第一个选择器的样式div
当它也是倒数第二个时div
(当只有两个div
s)。我使用两个声明只是为了可读性。
查看this http://cssdeck.com/labs/wuizu6uh demo.
但是,请确保对伪类的支持足以满足您的要求。This http://css-tricks.com/almanac/selectors/n/nth-last-of-type/#browser-support页(2013)指出:
:nth-last-of-type
在 CSS 选择器模块 3 中引入,这意味着旧版本的浏览器不支持它。然而,现代浏览器的支持是无可挑剔的,并且新的伪选择器广泛应用于生产环境中。如果您需要较旧的浏览器支持,请对 IE 进行 Polyfill,或者以非关键方式使用这些选择器(建议采用渐进式增强)。
This https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-last-of-type#Browser_compatibilityMDN 页面指出以下浏览器在给定版本中具有“基本支持”:
┌────────┬─────────────────┬───────────────────┬───────┬────────┐
│ Chrome │ Firefox (Gecko) │ Internet Explorer │ Opera │ Safari │
├────────┼─────────────────┼───────────────────┼───────┼────────┤
│ 4.0 │ 3.5 (1.9.1) │ 9.0 │ 9.5 │ 3.2 │
└────────┴─────────────────┴───────────────────┴───────┴────────┘
对于移动浏览器:
┌─────────┬────────────────────────┬───────────┬──────────────┬───────────────┐
│ Android │ Firefox Mobile (Gecko) │ IE Mobile │ Opera Mobile │ Safari Mobile │
├─────────┼────────────────────────┼───────────┼──────────────┼───────────────┤
│ 2.1 │ 1.0 (1.9.1) │ 9.0 │ 10.0 │ 3.2 │
└─────────┴────────────────────────┴───────────┴──────────────┴───────────────┘