Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selector for all but first of class

Tags:

css

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.

like image 797
Ben Foster Avatar asked Jan 26 '13 19:01

Ben Foster


People also ask

How do you select every element except first?

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.

How do I select all except first child CSS?

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.

How do I select all except first in CSS?

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!

How do I choose my first except child?

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.


2 Answers

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.

like image 182
Jon Avatar answered Oct 14 '22 23:10

Jon


If you want to select all other li.img and give them a different backgroundColor:

li.img ~ li.img {
   background-color: blue;
}
like image 44
axel.michel Avatar answered Oct 15 '22 00:10

axel.michel