Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS3 pseudo class not first and last child

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.

like image 671
haind Avatar asked May 30 '13 07:05

haind


People also ask

How do I skip the last child in CSS?

:not(:last-child) The :not() selector excludes the element passed to it from selection. The :last-child selector selects the last child.

How do you select all child elements in CSS except first?

We can very easily achieve this using the :not and :first-child selectors in a combination. For example, if you want to select all paragraphs except the first one that are inside a div element, you can use div :not(:first-child) selector.

How do you get not your first child in CSS?

Use the :not(selector) Selector Not to Select the First Child in CSS. We can use the :not(selector) selector to select every other element that is not the selected element. So, we can use the selector not to select the first child in CSS.

What is not (: first child?

ul:not(:first-child) means literally "any ul element that is not first child of its parent", so it won't match even the 1st ul if it's preceded by another element ( p , heading etc.). On the contrary, ul:not(:first-of-type) means "any ul element except the 1st ul in the container".


1 Answers

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

like image 60
Nick Andriopoulos Avatar answered Sep 30 '22 23:09

Nick Andriopoulos