If I have a list:

<ul>
    <li>item</li>
    <li class="selected">item</li>
    <li>item</li>
    <li>item</li>
</ul>

Is it possible to select the 3rd and 4th items in this list via CSS? And more generally, all items that come after/before the .selected item?

有帮助吗?

解决方案

To select the succeeding elements, you would use the general sibling combinator, ~.

Despite not being able to select the previous sibling elements, you could solve this by styling all the elements to begin with, and then overwriting the styling by selecting the succeeding elements.

EXAMPLE HERE

This will set the color of all the elements (except .selected) to red. It will then overwrite that styling and make the succeeding elements blue.

ul li:not(.selected) {
    color:red; 
}
ul .selected ~ li {
    color:blue;
}

Since :not() isn't supported in IE8, you could also use the following:

EXAMPLE HERE

ul li {
    color:red; 
}
.selected {
    color:black;
}
ul .selected ~ li {
    color:blue;
}

其他提示

There is a selector that matches elements preceded by another and this selector is a tilde ~.

So, you can simply match all elements after .selected using:

.selected ~ LI

JSFiddle example.

For futher details, visit spec.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top