Seleccionar el penúltimo elemento con css


Ya sé de :el último hijo. Pero hay una manera de seleccionar el div:

<div id="container">
 <div>a</div>
 <div>b</div>
 <div>SELECT THIS</div> <!-- THIS -->
 <div>c</div>
</div>

NOTA: sin jQuery, solo con CSS

Author: alex, 2011-03-24

2 answers

En CSS3 tienes:

:nth-last-child(2)

Véase: https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-last-child

Nth-last-child Soporte del navegador:

  • Cromo 2
  • Firefox 3.5
  • Opera 9.5, 10
  • Safari 3.1, 4
  • Internet Explorer 9
 186
Author: Frosty Z,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-02-15 16:18:47

Nota: Publicó esta respuesta porque OP declaró más tarde en comentarios que necesita seleccionar los dos últimos elementos, no solo el penúltimo.


El :nth-child selector CSS3 es de hecho más capaz de lo que nunca imaginaste!

Por ejemplo, esto seleccionará los últimos 2 elementos de #container:

#container :nth-last-child(-n+2) {}

Pero esto es solo el comienzo de una hermosa amistad.

#container :nth-last-child(-n+2) {
  background-color: cyan;
}
<div id="container">
 <div>a</div>
 <div>b</div>
 <div>SELECT THIS</div>
 <div>SELECT THIS</div>
</div>
 43
Author: kapa,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-09 02:28:23