blog icon indicating copy to clipboard operation
blog copied to clipboard

CSS优先级扫盲

Open diamont1001 opened this issue 6 years ago • 0 comments

最近发现,挺多同学对 CSS 的优先级(权重)都了解不深,或者在学习的过程中比较容易忽略,一般也只知道「后来优先」这一原则,这里就整理一下做个扫盲贴吧!

  • 给目标元素直接添加样式,永远比继承的优先级高
  • 后来优先(覆盖原则)
  • 无视 DOM 树中的距离(body headerhtml header 是一样的)

权重表

通用选择器(*)< 标签元素(div) < 类(.) < 属性 < 伪类 < ID(#) < 内联

选择器 权重 举个例子
标签和伪元素 1 div, ::before
类、属性、伪类 10 .btn, [type="radio"], :hover
ID 100 #detail
内联 1000 style=""

:not 否定伪类在优先级计算中不会被看作是伪类。

权重计算

/* 权重:1 */
div {
}

/* 权重:10 */
.btn {
}

/* 权重:100 */
#detail {
}

/* 权重:10 + 1 = 11 */
.btn div {
}

/* 权重:100 + 1 = 101 */
#detail div {
}

/* 权重:100 + 10 + 1 = 111 */
#detail .btn div {
}

!important

使用 !important 将覆盖任何其他声明。 但是,不推荐使用 !important,能不用尽量别用,因为它会破坏样式表中固有的级联规则 ,使得调试找 bug 变得更加困难。

当两条相互冲突的带有 !important 的规则的声明被应用到相同的元素上时,拥有更大优先级的声明会被采用。

对于 !important,有几个建议:

  • 能不用则不用
  • 要用,也只能在独立页面用
  • 永远不要在全站范围的 css 上使用 !important
  • 永远不要在你的插件(组件/库)中使用 !important

补充

diamont1001 avatar Apr 04 '18 10:04 diamont1001