实例演示:选择器权重,常用伪类选择器
发布于:2022-04-23 15:40:57
次阅读
选择器权重
代码
<body> <ul> <li class="item1">权重(0,1,2)大于(0,1,1),所以背景色显示蓝色,而非橙色</li> <li class="item1">权重2</li> <li class="item2" id="weight">权重(1,0,1)大于(0,1,1),所以背景色显示蓝色,而非粉红色</li> <li class="item2">权重4</li> <li class="item3">权重5</li> <li class="item3">权重6</li> </ul> <style> /* id: 千位 , class: 百位 , tag: 个位 */ /* id: 1 , class: 0 , tag: 1 */ /* 权重(1,0,1) */ #weight {background-color: blue;} /* id: 0 , class: 1, tag: 2 */ /* 权重(0,1,2) */ ul li.item1 {background-color: cyan;} /* id: 0 , class: 1, tag: 1 */ /* 权重(0,1,1) */ li.item1 {background-color: orange;} li.item2 {background-color: violet;} /* id: 0 , class: 0, tag: 1 */ /* 权重(0,0,1) */ li {background-color: green;} </style></body>
效果

常用伪类选择器
代码
<body> <ul> <li>item1</li> <li>item2</li> <li>item3</li> <li>item4</li> <li>item5</li> <li>item6</li> <li>item7</li> <li>item8</li> <li>item9</li> <li>item10</li> <li>item11</li> <li>item12</li> <li>item13</li> <li>item14</li> </ul> <style> /* 匹配第1个 */ li:first-of-type{ color:orange } /* :nth-of-type(an+b) */ /* 匹配第4个 */ /* a=0,n=[0,1,...], b = 4 */ li:nth-of-type(4){ color:pink } /* a=-1 */ /* 取前3个 */ li:nth-of-type(-n+3) { background-color: yellow; } /* 取后3个 */ li:nth-last-of-type(-n+3) { background-color:lightseagreen; } /* 匹配第9个及之后 */ /* a=1,n=[0,1,...], b = 9 */ li:nth-of-type(n+9){ color:red } /* 匹配最后1个 */ li:last-of-type{ color: blue } </style> </body>
效果
