You could use :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;
}
The first selector will style the penultimate div
only if it is immediately preceded by an even occurrence of div
. The second selector is to style the first div
when it is also the penultimate div
(when there are only two div
s). I used two declarations merely for the sake of readability.
Check out this demo.
However, ensure that support of the pseudo-class is sufficient for your requirements. This page (2013) states:
:nth-last-of-type
was introduced in CSS Selectors Module 3, which means old versions of browsers do not support it. However, modern browser support is impeccable, and the new pseudo-selectors are widely used in production environments. If you require older browser support, either polyfill for IE, or use these selectors in non-critical ways á la progressive enhancement, which is recommended.
This MDN page states the following browsers have "basic support" as of the given versions:
┌────────┬─────────────────┬───────────────────┬───────┬────────┐
│ Chrome │ Firefox (Gecko) │ Internet Explorer │ Opera │ Safari │
├────────┼─────────────────┼───────────────────┼───────┼────────┤
│ 4.0 │ 3.5 (1.9.1) │ 9.0 │ 9.5 │ 3.2 │
└────────┴─────────────────┴───────────────────┴───────┴────────┘
And for mobile browsers:
┌─────────┬────────────────────────┬───────────┬──────────────┬───────────────┐
│ Android │ Firefox Mobile (Gecko) │ IE Mobile │ Opera Mobile │ Safari Mobile │
├─────────┼────────────────────────┼───────────┼──────────────┼───────────────┤
│ 2.1 │ 1.0 (1.9.1) │ 9.0 │ 10.0 │ 3.2 │
└─────────┴────────────────────────┴───────────┴──────────────┴───────────────┘