省流小助手:CSS的样式就像瀑布流一样,自顶向下选择优先级最高的样式,并应用它。
首先重要说明:CSS中的每一条样式规则都是被独立处理的,例如,backgroud-color: grey
和color: red
两条样式规则,浏览器会分开独立处理。
那么Cascade是如何决定一条样式的呢?
首先Cascade,会找它的源(origin),源的优先级从高到低:
- Author importance: 开发者编写的样式,并且附加
!importance
,例如backgroud-color: grey !importance
- Author:开发者编写的样式
- User agent:浏览器实现的样式,只有基本样式,一般比较丑
接着如果是开发者编写的样式,那么会接着找specificity,specificity有两种:
- 内联样式
- 选择器样式
当然,我们知道内联样式优先级最高,其次是选择器。
选择器可以分为三种:
- id选择器
- 类选择器
- 标签选择器
这三种数量可以自由组合,一套组合拳下来就不知道哪组样式优先级更高了,举个粒子:
比如有个header结构:
<header id="father" class="big">
<h1 id="son" class="small">
企鹅电竞YYDS
</h1>
</header>
它有如下样式:
header h1 { color: red; }
h1 .small { color: green; }
#father .small { color: black; }
header .class { color: yellow; }
#son h1 { color: brown; }
到底哪一组规则优先级更高?
我们需要有一个方法去确定。
我们知道选择器的优先级是:ID选择器 > 类选择器 > 标签选择器
做一个表格:
Selector | ID | Class | Tag | Notation |
---|---|---|---|---|
header h1 | 0 | 0 | 2 | 0,0,2 |
h1 .small | 0 | 1 | 1 | 0,1,1 |
#father .small | 1 | 1 | 0 | 1,1,0 |
header .class | 0 | 1 | 1 | 0,1,1 |
#father h1 | 1 | 0 | 1 | 1,0,1 |
我们就得到5组数据,根据选择器优先级,首先我们看有ID选择器的,只有第三组1,1,0
和第五组1,0,1
,接着对比他们的类选择器,可以看到,最终第三组1,1,0
胜出!它的样式有着最高的优先级。
接下来问题又来了,假设又增加一组:
header h1 { color: red; }
h1 .small { color: green; }
#father .small { color: black; }
header .class { color: yellow; }
#son h1 { color: brown; }
.father #son { color: black; } /* 新增一组 */
它的和第三组一样,notation都是1,1,0
那么最终胜出方式就是先来后到,也就是顺序order来决定。
第三组出现的顺序更早,那么它的优先级会更高!
最后还有一种方式可以确定样式的值,那就是继承(inheritance)。
能够继承的样式其实并不多,主要有几种:
- 字体:
color
,font
,font-family
,font-size
,font-weight
,font-variant
,font-style
,line-height
,letter-spacing
,text-align
,text-indent
,white-space
,word-space
- list属性:
list-style
,list-style-type
,list-style-position
,list-style-image
- table边框属性:
border-collapse
,border-spacing
好了,最终总结一下:
Reference
[1] CSS in Depth Keith J.Grant