关于前端:CSS-选择器权重和优先级

5次阅读

共计 2374 个字符,预计需要花费 6 分钟才能阅读完成。

群里忽然又聊到了 CSS 款式的权重,这个话题每隔一段时间就会呈现一次,然而每次都去搜寻找选择器权重的文章分享有点太麻烦了,
次要是配图,想要找到本人记忆里的那张图真的很麻烦😂,所以还是本人整顿一篇,当前间接分享本人的笔记就好了。
其实权重计算这个货色不麻烦,就是分 4 类:

  1. inlineStyle: 行内款式
  2. #ID: ID 选择器
  3. .Class: 类, 属性和伪类选择器
  4. Element: 元素和伪类元素选择器

简略的权重比拟 inline style > ID > Class > Element > * 这个应该不须要说了吧,次要是多个选择器混合应用时计算的问题。


大部分人想到 CSS 权重应该会首先想到这个图


图片起源: 扼要古代魔法

而后简略的依照这里的权重去计算出来后果去比拟

例如:

然而!

这样的计算会有一个问题,就是如果说某一项选择器超过了 10 个,那么是不是就会造成疑难,是否会升级
例如

// 1 个 ID 选择器
#demo {color:green}
// 11 个 class 选择器
.demo1 .demo2 .demo3 .demo4 .demo5 .demo6 .demo7 .demo8 .demo9 .demo10 .demo11 {color:red}

依照上边的计算形式,得出的后果就是 100:110,然而理论并不会被 11 个类选择器所笼罩。

所以其实,是一个相似数组的模式,其计算结果为 [0, 1, 0, 0] 比上 [0, 0, 11, 0]

这点能够从 W3C 标准 上看到,其实是分为 [A, B, C, D] 四类,而后去一对一去比拟,并不会被 进位 所影响。

!important

!important 是一个非凡的申明,W3C 将其与选择器权重计算辨别开,
然而很多文章中把他搁置到 A 类之前作为 第 0 类 权重,的确在理论工作中察看到的成果也统一,只不过不能通过反复申明 !important 来达到晋升权重的目标(Invalid property value)

但如果是继承下来的 !important 属性,则会被新的申明笼罩。

如果应用简写属性并且应用 !important 申明

Declaring a shorthand property (e.g., ‘background‘) to be “!important” is equivalent to declaring all of its sub-properties to be “!important“.

将简写属性(例如 ’background‘)申明为 “!important” 等同于将其所有子属性申明为 “!important”。

接下来看一个残缺的例子 <div class="demo-class1 demo-class2"><span> 测试文字 ABC</span></div> 的元素款式:

.demo-class1 {
  font: italic 12pt sans-serif !important;
  text-indent: 1em ! important; // 被笼罩
}
.demo-class2 {
  font-weight: bold; // 未失效
  font-size: 24pt; // 未失效
  line-height: 1.2 !important; // 失效
  text-indent: 1.5em !important; // 失效
}
.demo-class2 span {font-style: normal // 失效}

序幕

举荐的权重计算图


图片起源: CSS-Tricks

新版本中的选择器权重批改

在 W3C 最新版的 选择器文档 中,行内款式曾经从权重中移出了,权重变成了三类 [#ID, .Class, Element]

在浏览 W3C 标准中,发现有中有这样一句话

By default, rules in author style sheets have more weight than rules in user style sheets. Precedence is reversed, however, for “!important” rules. All user and author rules have more weight than rules in the UA’s default style sheet.

默认状况下,author style sheets(作者样式表) 中的规定比 user style sheets(用户样式表) 中的规定具备更大的权重。然而,对于 “!important” 规定,优先级相同。与 UA 的默认样式表中的规定相比,所有用户和作者规定的权重均更大。

其中的 Author Style sheetsUser Style sheets 是我没有遇到过的名词,UA 当然是浏览器 (用户代理) 默认款式,从查阅到的后果来看:

作者样式表 (Author Style sheets)
作为开发者的咱们为我的项目所配置的样式表

用户样式表 (User Style sheets)
浏览器为浏览站点的用户提供的一个批改以后站点款式的性能(个别都是浏览器插件实现)所生成的样式表

文档资源

CSS2 – 6.4 The cascade – W3C Recommendation
CSS2 – 6.4.2 !important rules – W3C Recommendation
CSS2 – 6.4.3 Calculating a selector’s specificity – W3C Recommendation
selectors – 16. Calculating a selector’s specificity – W3C Recommendation
Draft – 6.3. Important Declarations: the !important annotation – W3C Editor’s Draft

CSS 选择器的权重计算规定 – 扼要古代魔法
Day20:小事之 CSS 權重 (css specificity) – iT 邦幫忙
Specifics on CSS Specificity | CSS-Tricks
User style sheet vs Author style sheet | Treehouse Community

正文完
 0