Useful :nth-child Recipes | CSS-Tricks

Select Only the Fifth Element

li:nth-child(5) {
    color: green;   
}

To select the first element, you can use :first-child, or I bet you can guess how to alter the above to do it as well.

Select All But The First Five

li:nth-child(n+6) {
    color: green;   
}

If there were more than 10 elements here, it would select all of them beyond 5.

Select Only The First Five

li:nth-child(-n+5) {
    color: green;   
}

Select Every Fourth, Starting At The First

li:nth-child(4n-7) {  /* or 4n+1 */
    color: green;   
}

Select Only Odd or Even

li:nth-child(odd) {
    color: green;   
}

li:nth-child(even) {
    color: green;   
}

Select The Last Element

li:last-child {
    color: green;
}

Selects the 10th because we have 10 elements here, but if there was 8 it would select the 8th, or if there were 1,290 it would select the 1,290th.

Select the Second to Last Element

li:nth-last-child(2) {
    color: green;
}

Selects the 9th because we have 10 elements here, but if there were 30 elements it would select the 29th.

Wanna play?

Try the tester.

Browser Support

Interestingly enough, :first-child was supported by IE 7, but it’s not until IE 9 where the rest of this stuff is supported. Other than IE there isn’t much browser support concern, and if you are worried about IE, then useSelectivizr. If browser support stuff is interesting or important for you, definitely check out When can I use… which tracks this stuff very well.

소스: Useful :nth-child Recipes | CSS-Tricks

댓글 남기기

이메일은 공개되지 않습니다. 필수 입력창은 * 로 표시되어 있습니다