Article Introduction: when I want the perfect use: Nth-child or: Nth-of-type is a little dizzy. The more you understand them, the better CSS rules you can write! |
Translated from: useful:nth-child recipies
Chinese: useful: The secret ingredient of Nth-child
Please respect the copyright, reproduced please indicate the source, thank you!
When I want the perfect use: Nth-child or: Nth-of-type is a little dizzy. The more you understand them, the better CSS rules you can write!
In these simple "recipes" (which are actually expressions) I will repeat the use of a simple list and then select the number. But it's obvious that it's easy to change them to get a similar selector.
Select only the Fifth Element
1
2
3
|
Li:nth-child (5) {
color:
green;
} |
To select the first element, you can use: First-child, or I believe you can also change the above example to achieve.
Select all elements except the previous five
Li:nth-child (n+6) {
color:
green;
}
If there are more than 10 elements, it will select more than 5.
Select only the previous 5
1
2
3
|
Li:nth-child (-n+5) {
color:
green;
} |
From the beginning, choose every fourth
1
2
3
4
|
Li:nth-child (4n-7)
{/
* or 4n+1/
color:
green;
} |
Select Odd or even
1
2
3
|
Li:nth-child (odd) {
color:
green;
} |
1
2
3
|
Li:nth-child (even) {
color:
green;
} |
Of course there are two other implementations, you know--God fly
Select the last Element
1
2
3
|
Li:last-child {
color:
green;
} |
Select the second-lowest
1
2
3
|
Li:nth-last-child (2) {
color:
green;
} |
As you can see from this example, the above example also has the second implementation method.
Browser support
Interestingly,: First-child and: Last-child is supported by IE 7, but knows IE9 only supports the remaining selectors. If you are worried about IE, you can use selectivizr. If your browser compatibility is important to you, please pay attention to when can I use ...
Well, using the CSS3 selector is a fun thing to do, like a simple math problem.