HTML代码
1 2 3 4 5 6 |
<article> <p>First paragraph...</p> <p>Lorem ipsum...</p> <p>Dolor sit amet...</p> <p>Consectetur adipisicing...</p> </article> |
CSS选择第一个子元素:
1 2 3 |
article > p:first-child { background:red; } |
CSS选择第二个子元素:
1 2 3 4 |
article > p:nth-child(2) { background:red; } |
CSS选择最后一个子元素:
1 2 3 |
article > p:last-child { background:red; } |
css选择器奇数偶数:
1 2 3 4 5 6 7 8 |
article > p:nth-child(odd) #CSS选择奇数行 { background:red; } article > p:nth-child(even) #CSS选择偶数行 { background:green; } |
注意:如需选择DIV中的元素将article更改为div 例:div > p:first-child
同样适用于:first-child
:last-child
:nth-child
,如需选择非段落P的元素更改为相应的元素标签即可。