CSS的nth-child选择器的探讨
有哪些nth-child
这是一个系列的选择器,可供我们在各种情况下使用,包括
1:first-child
2:first-of-type
3:last-of-type
4:only-of-type
4:only-child
5:nth-child(n)
6:nth-last-child(n)
7:nth-of-type(n)
8:nth-last-of-type(n)
9:last-child
具体每个的差异可以去CSS参考手册了解,这里只针对nth-child的使用进行探讨。
Tips
ie8以下的存在兼容性问题,不过随着微软宣布不再对ie8的维护,想必以后ie不再会是前端开发者的噩梦吧。
典型使用
1.选取第n个你想要的标签 .ui-item li:nth-child(2) { color: red; }
2.选取大于特定值(如4)的标签 .ui-item li:nth-child(n + 4) { color: red; }
3.选取小于特定值(如4)的标签 .ui-item li:nth-child(4 - n) { color: red; }
4.第偶数个标签 .ui-item li:nth-child(2n) { color: red; } 或者 .ui-item li:nth-child(even) { color: red; }
5.第奇数个标签 .ui-item li:nth-child(2n - 1) { color: red; } 或者 .ui-item li:nth-child(odd) { color: red; }
探讨
关于正确选取想要的节点,我曾经犯过一个错,希望大家引以为戒吧

我想要选取ui-item下的第一个div让其变为红色,于是有了 .ui-item div:nth-child(1) { color: red;},然后发现并没有如我所想要的那样讲ui-item下的第一个div变红。
正确的选取方式应该是.ui-item div: nth-child(2) { color : red;} 因为上面那种方式选取的是第一个节点,他的节点类型是p而不是div,故不能正确选择。
parantNode nodeType: nth-child(n)这种选择方式的意思是,选取父元素下的第n个元素,同时节点类型为指定的类型 。
浙公网安备 33010602011771号