12

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.

4

3 回答 3

26

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.

于 2013-01-26T19:24:06.167 回答
9

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

li.img ~ li.img {
   background-color: blue;
}
于 2013-01-26T19:23:44.433 回答
-2

May be, you could add a javascript like in case IE 8 (and older) or such browser does not support ~ selector as told by Jon above:

document.getElementsByClassName("img")[0].style.backgroundColor = "red";
于 2013-01-26T19:40:12.867 回答