문제

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