作为页面作者,我们可以对我们的HTML使用多个样式表,用户也可能提供自己的样式,另外浏览器也有默认样式。而且,不仅如此,还可以有多个选择器应用到同一个元素。那么,如何确定一个元素究竟应用哪些样式呢?
实际上,这就是在问层叠的作用,只是问法不同。给定一组样式表中的一组样式,浏览器就是以层叠方式来确定具体使用哪一种样式。而本篇博文将会详细讲述浏览器采取的规则,即是Rule conflicts algorithm。
CSS的全称:Cascade style sheet。 style sheet是指样式表,这我就不多说了。而Cascade,便是层叠,也是本文的核心,下面我将详细讲述。
1.与层叠相关的因素
Origin
(1)the web page author
(2)the browser user configuration
(3)the browser default configurationOrder
the order after all css rules insertedSpecificity
a four digits number for each ruleimportancy
a rule is with or without !important modifier
样式表的来源:网页作者>用户设置>浏览器默认设置;
顺序:规则声明靠后者优先;
特异值: 特定值排序,高者优先;
重要性声明:在规则声明后加!important者优先。
2.特异值的计算规则
(1)the specificity of a CSS selector is a four digits number likes abcd
(2)Count 1 if the styles are applied from the HTML style attribute, and 0 otherwise; this becomes variable a.
(3)Count the number of ID attributes in the selector; the sum is variable b.
(4)Count the number of attributes, pseudo-classes, and class names in a selector; the sum is variable c.
(5)Count the number of element names in the selector; this is variable d.
(6)Ignore pseudo-elements.
(7)when two conflict rules has same specificity, the one occurs later is style sheet file wins
(8)at last, a rule with !important overrides precedence!
特异值可以看作一个四位数abcd, 起始值为0000:
1.当出现<style>
标签时,a位+1,即1000;
2.当出现ID选择器时,b位+1, 即0100;
3.当出现属性,伪类选择器,类选择器时,c位+1, 即0010;
4.当为普通的HTML标签时,d位+1,即0001.
下面的图呈现了部分例子:
3.样式排序流程
第一步,按照下面的比较进行排序:
用户配置中的重要规则>网页作者的重要规则>网页作者的普通规则>用户配置中的普通规则>浏览器默认设置中的普通规则
第二步,按照下面的规则进行二次排序:
(1)特异值最高的重要规则胜出;
(2)无重要规则,则特异值最高的普通规则胜出;
(3)若两条规则重要性、特异值相同,在第一步给出的来源排序中靠前的胜出;
(4)若两条规则重要性、特异值、来源都相同,则在来源文件中按照说明的规则顺序,后出现的胜出。
4.总结
相信讲到这里,你对层叠也就有了较为完整的认识,对于浏览器处理样式冲突的原理也就很容易理解了。最后希望这篇文章能给你们带来帮助。
以上内容皆为本人观点,欢迎大家提出批评和指导,我们一起探讨!