Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

CSS 层叠值的计算和CSS的继承 #7

Open
mbaxszy7 opened this issue Jun 17, 2020 · 0 comments
Open

CSS 层叠值的计算和CSS的继承 #7

mbaxszy7 opened this issue Jun 17, 2020 · 0 comments
Labels

Comments

@mbaxszy7
Copy link
Owner

整理一下CSS层叠值的计算和CSS的继承

层叠值的计算

层叠值: 浏览器遵循三个步骤,即来源、优先级、源码顺序,来解析网页上每个元素的每个属性

!!!不推荐使用!important,因为!important没有层叠值可言。

当在一个样式声明中使用一个 !important 规则时,此声明将覆盖任何其他声明

  1. 来源: 样式是从哪里来的,包括你书写的样式和用户代理默认样式等
  2. 优先级
 [0,0,0,0] -> [行内,id, class, 标签]
根据以上对应关系统计每个选择器的个数作为指数,然后再给一个很大的基数,结果值就是相加值。栗子如下(基数取1000):

div#a.b .c[id=x]
属性选择器[id=x] 跟 class选择器 .b .c 权重一致
[0, 1, 3, 1]
1000^0 + 1000^1 + 1000^3 + 1000^1

#a:not(#b)
:not 不参与权重计算
[0, 2, 0, 0]
1000^0 + 1000^2 + 1000^0 + 1000^0

*.a
通用选择器*  不参与权重计算
[0, 0, 1, 0]
1000^0 + 1000^0 + 1000^1 + 1000^0

div.a
[0, 0, 1, 1]
1000^0 + 1000^0 + 1000^1 + 1000^1

伪类选择器(如 :hover )和属性选择器(如 [type="input"] )与一个类选择 器的优先级相同。
通用选择器( * )和组合器( > 、 + 、 ~ )对优先级没有影响(不参与权重计算)。

通常最好让优先级尽可能低,这样当需要覆盖一些样式时,才能有选择空间

  1. 源码顺序: 样式在样式表里的声明顺序
    如果两个声明的来源和优先级相同,其中一个声明在样式表中出现较晚,或者位于页面较晚引入的样式表中,则该声明胜出。

CSS的继承(继承属性 (inherited property))

当没有给元素的继承属性指定一个值的时候,该属性会取父元素的同属性的计算值 computed value。
但不是所有的属性都能被继承。默认情况下,只有特定的一些属性能被继承,通常是我们希望被继承的那些。它们主要是跟文本相关的属性:color、font、font-family、font-size、 font-weight、font-variant、font-style、line-height、letter-spacing、text-align、 text-indent、text-transform、white-space 以及 word-spacing。

@mbaxszy7 mbaxszy7 added the css label Jun 17, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant