CSS优先级与继承
CSS优先级与继承是样式生效的核心机制,理解它们才能写出可控的CSS。
优先级权重
| 来源 | 权重 | |
|---|---|---|
| 内联样式 | 1000 | |
| ID选择器 | 100 | |
| 类/伪类/属性选择器 | 10 | |
| 标签/伪元素选择器 | 1 | |
| 通配选择器 | 0 |
权重计算
CSS
/* 权重:1 */
p { color: gray; }
/* 权重:10 */
.text { color: blue; }
/* 权重:100 */
#title { color: red; }
/* 权重:11(10+1) */
p.text { color: green; }
/* 权重:101(100+1) */
div#header { color: purple; }
/* 权重:12(10+10) */
.box.active { color: orange; }
权重相加,值越大优先级越高。
权重比较规则
CSS
/* 高权重覆盖低权重 */
#box { color: red; } /* 100 */
.box { color: blue; } /* 10 */
/* 最终显示红色 */
/* 权重相同,后定义生效 */
.text { color: blue; }
.text { color: green; }
/* 最终显示绿色 */
!important 强制最高
CSS
.box {
color: blue !important; /* 强制生效 */
}
#box {
color: red;
}
/* 最终显示蓝色 */
注意:
!important会破坏优先级规则,应尽量避免使用。
CSS继承
子元素自动继承父元素的某些属性:
可继承属性
CSS
body {
font-family: Arial;
color: #333;
line-height: 1.6;
}
/* 子元素自动继承 */
p {
/* 继承 font-family、color、line-height */
}
| 可继承属性 | 说明 | |
|---|---|---|
| font-* | 字体相关 | |
| color | 文字颜色 | |
| line-height | 行高 | |
| text-* | 文本相关 | |
| list-style | 列表样式 | |
| visibility | 可见性 |
不继承属性
CSS
.parent {
border: 1px solid #333;
padding: 10px;
margin: 10px;
}
/* 子元素不继承 border、padding、margin */
| 不继承属性 | 说明 | |
|---|---|---|
| border | 边框 | |
| padding | 内边距 | |
| margin | 外边距 | |
| width/height | 尺寸 | |
| background | 背景 | |
| position | 定位 |
强制继承
CSS
.parent {
border: 1px solid red;
}
.child {
border: inherit; /* 强制继承父元素边框 */
}
inherit 与 initial
CSS
/* inherit:继承父元素值 */
.box {
color: inherit;
}
/* initial:重置为默认值 */
.box {
display: initial;
}
/* unset:可继承则继承,否则重置 */
.box {
margin: unset;
}
要点总结
- 优先级权重:内联 > ID > 类 > 标签 > 通配
- 权重相加比较,值大者优先
- 权重相同时,后定义生效
- 字体、颜色、文本属性可继承
存放路径:articles/CSS/入门/CSS选择器/CSS优先级与继承.md
📝 发现内容有误?点击此处直接编辑