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.
:not(:last-child) The :not() selector excludes the element passed to it from selection. The :last-child selector selects the last child.
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.
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.
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".
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With