批改状态:合格
老师批语:
将3种选择器分别看做权重的千位、百位、个位
- id: 千位
- class: 百位
- tag: 个位
在编辑器中降鼠标提留在选择器上也可以看到权重
<h1>选择器的权重</h1>
h1 {color: pink;}

此时使用标签h1选中,id:0,class:0,tag:1,故权重计算=0,0,1。
<h1 class="header">选择器的权重</h1>
.header {color: red;}h1 {color: pink;}

h1的权重是(0,0,1)而.header的权重计算是(0,1,0),权重大的会覆盖权重小的,所以文字显示为红色。
<h1 class="header" id="head">选择器的权重</h1>
#head {color: gray;}.header {color: red;}h1 {color: pink;}

id选择器的权重是(1,0,0),比类和标签都大,所以显示灰色(由于id选择器的权重过大,在开发中一般不建议使用)。
如何在不使用id选择器的情况下,使权重高于类选择器?
<h1 class="header" id="head">选择器的权重</h1>
.header {color: red;}h1.header {color: pink;}

只要在标签选择器后面加上类,这样计算权重就=(0,1,1)>(0,1,0),文字的颜色就会变回粉色(其他增加权重的方法类似)。
在权重的计算中,如果在属性后面加上!important,那么会优先显示该条属性,而后再依据权重显示。
<h1 class="header" id="head">选择器的权重</h1>
#head {color: gray;}h1 {color: red !important;}

.list>li:first-of-type {background-color: pink;}

.list>li:last-of-type {background-color: pink;}

.list>li:nth-of-type(4) {background-color: pink;}

.list>li:nth-last-of-type(4) {background-color: pink;}

:nth-of-type(an+b)1. a: 系数, [0,1,2,...]2. n: [0,1,2,3,....]3. b: 偏移量, 从0开始注: 计算出来的索引,必须是有效, 从1开始
实例计算
.list> :nth-of-type(-n + 3) {background-color: lightgreen;}
计算过程:(-1x0 + 3 = 3;-1x1 + 3 = 3-1 = 2;-1x2 + 3 = 3-2 = 1;-1x3 + 3 = 3-3 = 0)

.list> :nth-of-type(odd) {background-color: lightgreen;}.list> :nth-of-type(even) {background-color: lightgreen;}


odd为奇数, even为偶数。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号