我用的是VSCode,写Html代码
当时我正在愉快的刷着前端教程,其中有一期专门讲了CSS优先级计算方式,上面说,权重叠计算公式:(每一级之间不存在进位)
(行内样式的个数,id选择器的个数,类选择器的个数,标签选择器的个数)
比较规则:
先比较第一级数字,如果比较出来了,之后的统统不看
如果第一级数字相同,此时再去比较第二级数字,如果比较出来了,之后的统统不看
以此类推
如果最终所有数字都相同,表示优先级相同,则比较层叠性(谁写在下面,谁说了算)
可是我去用了一下,发现了好像不太对,具体代码和结果后面会有,我就去问了我的同事,他们也不知道是怎么回事
html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Documenttitle>
<style>
/* (0, 1, 0, 1) */
span #box {
color: red;
}
/* (0, 0, 2, 0) */
.bigBox .box {
color: green;
}
/* (0, 0, 1, 1) */
.bigBox span {
color: blue;
}
/* (0, 0, 0, 2) */
div span {
color: black;
}
style>
head>
<body>
<div class="bigBox" id="bigBox">
<span class="box" id="box">spanspan>
div>
body>
html>
按道理,字体颜色应该是red,可在运行结果中,那个字体却是绿色的,这是怎么回事
我尝试过重新安装VSCode,HTML和CSS,但还是没用,仍旧是一样的效果
希望各大网友能帮助一下我,谢谢,好人一生平安
因为 span #box 这个是属于标签样式,最先初始化
.bigBox .box 这个是等初始化完毕再付给 标签
span #box的意思是 span 的后代 #box color:red . 你改成 span ,#box 就行了
审查会发现 red 根本没加上 。因为用错 选择器了
组合选择器权重是相加的结果
确实是span#box的优先级最高,为0,1,0,1.只不过你写错样式内容了,中间是没有空格的
span#box {} // 应该写成这样,这两个是同级关系
span #box {} // 这样写是错的,变成父子关系了,不存在这个样式,所以也没生效
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
/* (0, 1, 0, 1) */
span,
#box {
color: red;
}
/* (0, 0, 2, 0) */
.bigBox .box {
color: green;
}
/* (0, 0, 1, 1) */
.bigBox span {
color: blue;
}
/* (0, 0, 0, 2) */
div span {
color: black;
}
</style>
</head>
<body>
<div class="bigBox" id="bigBox">
<span class="box" id="box">span</span>
</div>
</body>
</html>
span #box意思是找span元素后代中id是box的元素,找不到这个元素自然没有生效,在span和#box之间加上逗号就行,改为span,#box