你可以使用: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
时)。为了便于阅读,我仅使用了两个声明。
退房this演示。
但是,确保伪类的支持足以满足您的要求。 This页(2013年)规定:
:nth-last-of-type
在CSS选择模块3,这意味着老版本的浏览器不支持它进行了介绍。但是,现代浏览器的支持是无懈可击的,新的伪选择器广泛应用于生产环境。如果您需要较旧的浏览器支持,或者为IE添加填充,或者以非关键方式使用这些选择器,那么推荐使用渐进式增强。
This MDN页面状态下浏览器有“基本支持”为给定的版本:
┌────────┬─────────────────┬───────────────────┬───────┬────────┐
│ 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 │
└─────────┴────────────────────────┴───────────┴──────────────┴───────────────┘
,你可以用'获得通过:第n -of-type(偶数):last-child:before',而不是必须在前一个元素上执行':after'? – 2014-10-04 01:35:32