|
2019-05-17
当 html
元素拥有多个 css
样式时,浏览器会根据优先级规则计算 css
,如果对优先级规则不够熟悉,在实际的开发过程中往往会产生很多困扰,本文总结css的优先级规则。
分析下面的demo:
<html id="further"> <body class="close"> <h1>Here is a title!</h1> </body> </html>
当DOM元素的指定样式来自继承时,只与DOM树中的距离相关,与选择器的顺序和优先级( id>class 下面会讲到)无关,下方的css会渲染文字为紫色,因为 h1
更靠近 .close
,尽管从选择器类型上 #further
优先级更高。
.close { color: purple; } #further { color: green; }
当DOM元素的css并非通过继承而来,则会无视DOM树中的距离,若多个css平级,则后面加载的css会覆盖前面的css,下方的css为平级,会根据加载顺序渲染文字为紫色。
body h1 { color: green; } html h1 { color: purple; }
css常见选择器有7类:
#id{}
.class{}
a[href="csxiaoyao.com"]{}
:hover{}
span{}
::before{}
*{}
此外,再算上内联样式(元素上的style属性)和继承的样式,可以形成优先级关系链:
内联样式
> ID 选择器
> 类选择器
= 属性选择器
= 伪类选择器
> 标签选择器
= 伪元素选择器
> 通用选择器
> 继承的样式
根据上述优先级关系链,下方div中文字为黑色。
<div id="content-id" class="content-class" style="color: black">demo</div> <style> #content-id { color: red; } .content-class { color: blue; } div { color: grey; } </style>
在下方的案例中,尽管选择器 *[id="foo"]
通过ID选择了一个元素,但它还是作为一个属性选择器来计算自身的优先级,低于 ID 选择器,所以p标签内的文字为绿色。
<p id="foo">I am a sample text.</p> <style> #foo { color: green; } [id="foo"] { color: purple; } </style>
所有 CSS 的选择符都为上述 7 种基础选择器或组合而成,当多个选择器组合时,首先需要计算 abcd 四个值:
ID 选择器
出现的次数类选择器
、属性选择器
、伪类选择器
出现的总次数标签选择器
、伪元素选择器
出现的总次数
首先比较是否使用内联样式,a
的优先级最高,如果 a
相同,按 b
、c
、d
的顺序依次比较大小,大的则优先级高,相等则比较下一个。若 b
、c
、d
都相等,则按加载顺序判定,下例中两个css优先级相同,此时后面的覆盖前面的css,文字颜色为红色。
<div class="outer"> <span class="inner">test</span> </div> <style> div .inner { color: blue; } .outer span { color: red; } </style>
注意:
:not
否定伪类不参与优先级计算
!important
是一种强制改变css优先级的方法,它拥有最高优先级,若同时多个css有 !important
,则再根据上述规则判断优先级。下例是一种常见的场景:由于元素使用了选择器中优先级最高的内联样式,无法再通过选择器修改颜色,只能使用 !important
,此时文字为蓝色。
<div class="foo" style="color: red;">test</div> <style> .foo[style*="color: red"] { color: blue !important; } </style>
注意:
Always 一定要优化考虑使用样式规则的优先级来解决问题而不是
!important
Only 只在需要覆盖全站或外部 CSS 的特定页面中使用!important
Never 永远不要在你的插件中使用!important
Never 永远不要在全站范围的 CSS 代码中使用!important
编辑:航网科技 来源:腾讯云 本文版权归原作者所有 转载请注明出处
微信扫一扫咨询客服
全国免费服务热线
0755-36300002