CSS3 pseudo class not first and last child

haind picture haind · May 30, 2013 · Viewed 38.1k times · Source

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.

Answer

Nick Andriopoulos picture Nick Andriopoulos · May 30, 2013

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).