CSS3 pseudo class not first and last child

Problem

I have some following HTML code:

<ul>
    <li>number 1</li>
    <li>number 2</li>
    <li>number 3</li>
    <li>number 4</li>
    <li>number 5</li>
    <li>number 6</li>
    <li>number 7</li>
    <li>number 8</li>
    <li>number 9</li>
    <li>number 10</li>
</ul>

How can I use CSS3 pseudo-classes to make any li element which is not the first or last have a background-color of tomato for example? It seems that I could use the :not selector.

Problem courtesy of: haind

Solution

Two ways :

you can set a generic rule, and then override it for :first-child and :last-child items. This plays to CSS strengths:

 li { background: red; }
 li:first-child, li:last-child { background: white; }

Or, you can use the :not keyword combined combining the two:

li { background: white; }
li:not(:first-child):not(:last-child) { background: red; }

Of the two, I personally prefer the first - it's easier to comprehend and maintain (in my opinion).

Solution courtesy of: hexblot

Discussion

Here's a pen http://codepen.io/vendruscolo/pen/AeHtG

You have to combine two :not() pseudo classes:

li:not(:first-child):not(:last-child) {
  background: red;
}

Here's the MDN documentation: as stated there, it's not supported on IE < 9, while it's well supported on other browsers.

If you need IE 8 support, you have to rely on Javascript or use another class to indicate which element is the last child. In fact, IE 8 (and lower) doesn't support the :last-child pseudo class.

Discussion courtesy of: Alessandro Vendruscolo

This recipe can be found in it's original form on Stack Over Flow.