CSS – initial, Inherit, unset, revert
参考
Understanding the “Initial”, “Inherit” and “Unset” CSS Keywords
【译】理解CSS关键字:“Initial”,“Inherit”和“Unset”
属性, 固定值, 相关值, 元素
display, width 是属性
block, inline, px 是固定值
inherit, initial, rem 是相关值
<div>, <span> 是元素
user agent stylesheet
当没有写任何 style 时, 某一些元素配上某些属性会有 user agent stylesheet (游览器默认样式)
比如 div + display = block, span + display = inline, h2 + font-size = 1.5em.
initial
initial 是相关值, 依据不同的属性会有不同的 value.
去查 MDN 就可以看到每一个元素的 initial value 了
display: initial 相等于 display: inline
initial 只看属性, user agent style 看属性 + 元素, 这是 2 者最大的区别, 所以,
div { display: initial } 和 span { display: initial } 结果都是 display: inline
而 user agent style, div + display = block, span + display = inline.
inherited property
有些属性有 cascade 效果, 比如 font-size, color (文本属性都有),
当给 html { font-size: 1.5rem } 后, 所有的子孙元素的 font-size 都会变成 1.5rem, 这些属性被称为 inherited property
非文本属性 width, display, position 则不会 cascade, 它们被称为 non-inherited property.
MDN 上有注明属性是否是 inherited
display 属性
font-size 属性
inherit
inherit 是相关值, 它会去找 parent element 的属性值, 如果 parent 也是 inherit 就继续往上找, 如果 parent 没有 set 那就用 parent 的 user agent style, 如果没有 user agent style 就用 initial 值.
unset
对于 inherited property, unset 和 inherit 是一样的.
对于 non-inherited property, unset 和 initial 是一样的.
当 selector 匹配超过一个元素时才会用到 unset, 比如 * { display: unset }
不然用 inherit 或 initial 就够了
revert
revert 和 unset 是一样的, 唯一的区别是它是用 user agent style 而不是 initial 值 (当然如果没有 user agent style 就用 initail)
总结:
1. initial != user agent style, initial 只关心属性, user agent style 关心元素 + 属性
2. inherited property 指的是那种在 parent set style 会 cascade 到子孙的, 比如 font-size, color (文本 style).
non-inherited property 就是其它不会 cascade 的, 比如 width, display, position
3. inherited property + unset = inherit
non-inherited property + unset = initial
4. inherited property + revert = inherit
non-inherited property + revert = user agnet style
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
· 上周热点回顾(2.17-2.23)