HTML:
<ul>
<li></li>
<li></li>
<li class="img"></li>
<li></li>
<li class="img"></li>
<li class="img"></li>
<li></li>
</ul>
CSS:
ul {
list-style-type: none;
}
li {
background-color: red;
margin: 5px;
width: 30px;
height: 30px;
float: left;
}
li.img:not(:first-child) {
background-color: blue;
}
Result:
http://jsfiddle.net/benfosterdev/K3ZnA/
I want all but the first li.img
to have a blue background.
How to Select all Elements Except the First With the CSS :not(:first-child) Selector. Learn how to select all HTML elements except the first with the CSS `:not(:first-child) selector. If you add the following rule-set to your CSS stylesheet, every h2 element on your entire website will get a 64px top margin.
To do that we have to use to the :nth-child(N) selector which allows you to select any nth element from the document. The number N can be 1, 2, 3, 4, 5,….. up to n. For example, If you want to select all paragraphs except the third one which are inside a div element you have to use div p:not(:nth-child(3)) selector.
The trick is very easy, in CSS we have the sibling selector ("+"), if i will make selector that choose "li + li" it will select all list-items except the first . That's all!
This selector is used to select every element which is not the first-child of its parent element. It is represented as an argument in the form of :not(first-child) element. Explanation: The above example shows that a <div> is a container Tag.
You cannot do this with :not(:first-child)
because all li.img
elements except the first li
(no matter if it's .img
or not) are indeed not the first child of their parent. So that selector would exclude the first li.img
only if it were the first li
without qualification.
However, you can do it with the general sibling combinator ~
:
li.img ~ li.img {
background-color: blue;
}
This selector matches any li.img
that is the sibling of any other li.img
but appears after it in document order, or in other words every li.img
but the first.
See it in action, and be aware that IE < 9 does not support this selector.
If you want to select all other li.img and give them a different backgroundColor:
li.img ~ li.img {
background-color: blue;
}
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