选择器的优先级关系到元素应用哪个样式。在css2.1的规范(http://www.w3.org/tr/2009/cr-css2-20090908/cascade.html#specificity)中是这样描述的:
如果声明来自于“style”属性,而不是带有选择器的规则,则记为 1,否则记为 0 (= a)(html元素的style属性也是样式规则,因为这些样式规则没有选择器,因此记为a=1,b=0,c=0,d=0)计算选择器中 id 属性的个数 (= b)计算选择器中其他属性(类、属性选择器)和伪类的个数 (= c)计算选择器中元素名称和伪元素的个数 (= d)将四个数字按 a-b-c-d 这样连接起来(位于大数进制的数字系统中),构成选择器的优先级。
在最新的selector level 3规范中:
计算选择器中 id 属性的个数 (= a)计算选择器中其他属性(类、属性选择器)和伪类的个数 (= b)计算选择器中元素名称和伪元素的个数 (= c)忽略通用选择器*将三个数字按 a-b-c这样连接起来(位于大数进制的数字系统中),构成选择器的优先级。style属性计算参考css2.1规范。
问题:1、选择器的整体优先级如何计算,是像网上说的a*1000+b*100+c*10+d吗? 答:不是。这种回答明显是望文生义。四级(a、b、c、d)之间并不是简单的相加关系。同一级(例如:a对a)的才具有可比关系。
分析:
以下为webkit的webcore中关于优先级计算的代码(http://trac.webkit.org/browser/trunk/source/webcore/css/cssselector.cpp)
unsigned cssselector::specificity() const{ // make sure the result doesn't overflow static const unsigned maxvaluemask = 0xffffff; // 整个选择器的最大值,十进制表示:idmask + classmask + elementmak = 16777215 static const unsigned idmask = 0xff0000; // id选择器的最大值,十进制表示:(16*16+16)*16^4=16711680 static const unsigned classmask = 0xff00; // class(伪类、类)选择器的最大值,十进制表示:(16*16+16)*16^2=65280 static const unsigned elementmask = 0xff; // 元素选择器的最大值,十进制表示:16*16+16=255 if (isforpage()) return specificityforpage() & maxvaluemask; unsigned total = 0; unsigned temp = 0; for (const cssselector* selector = this; selector; selector = selector->taghistory()) { temp = total + selector->specificityforoneselector(); // clamp each component to its max in the case of overflow. if ((temp & idmask) idmask)) // 判断是否为id选择器 total |= idmask; // 保证id选择器的同类叠加不会超过id选择器的总最大值,下同 else if ((temp & classmask) classmask)) total |= classmask; else if ((temp & elementmask) elementmask)) total |= elementmask; else total = temp; } return total;}inline unsigned cssselector::specificityforoneselector() const{ // fixme: pseudo-elements and pseudo-classes do not have the same specificity. this function // isn't quite correct. switch (m_match) { case id: return 0x10000; // id选择器权重 case pseudoclass: // fixme: psuedoany should base the specificity on the sub-selectors. // see http://lists.w3.org/archives/public/www-style/2010sep/0530.html if (pseudoclasstype() == pseudoclassnot && selectorlist()) return selectorlist()->first()->specificityforoneselector(); fallthrough; case exact: case class: case set: case list: case hyphen: case pseudoelement: case contain: case begin: case end: return 0x100; // class选择器权重 case tag: return (tagqname().localname() != staratom) ? 1 : 0; // 元素选择器权重 case unknown: return 0; } assert_not_reached(); return 0;}
从上面的代码可以看出,在webkit中,对于a级选择器(“style”属性的样式规则),根本不参与优先级运算的过程。对于b级(id选择器)、c级(class选择器)、d级(元素选择器),每一级都有自己的最大值(最大数目255),超出时就会应用其最大值(最大数目)。b级最大值为0xff0000(16711680),权重为0x1000(65536),数目超过256时仍然使用最大值。c级、d级相似。所以并不存在低一级超出一定数目后导致高一级进一出现覆盖的情况。在一个选择器组(em:#a .d div)中,所有选择器的加和不会超过16777215(每一类的选择器都保证了不会超出最大值的情况)。demo:http://jsbin.com/duker/2。对于!important,webkit是走的另一条路径(具有!important的样式规则大于没有!important的样式规则,只有在同时具有!important属性时才会比较选择器的整体优先级)。整体来说,在webkit中,!important>inline style>id>class>tag。
webkit是在http://trac.webkit.org/changeset/130444/trunk/source/webcore/css/cssselector.cpp这一次的修订中加上对于优先级溢出的处理的(chrome发布版本很快,今年改用了blink,可以认为chrome都遵守了特殊性(优先级)计算的标准):
时间戳:2012-10-04 19:04:44 (20个月前)作者:commit-queue@webkit.org消息:选择器特殊性类别溢出到高类别
https://bugs.webkit.org/show_bug.cgi?id=98295
patch by tab atkins jackalmage@gmail.com> on 2012-10-04
reviewed by eric seidel.
这一次添加的补丁是为了对于css选择器的特殊性添加溢出策略。
以前我们并不会检测每个类别的特殊性溢出问题。原始的策略是:把每个类别存储为一个字节(2^8=256),然后整体存在一个无符号整型数中。这样的话就会导致256个同一类别的单选择器等于1个高类别的选择器。但是这违反了选择器的特殊性规则,导致样式规则排序问题。
tests: /fast/selectors/specificity-overflow.html
css/cssselector.cpp:(webcore::cssselector::specificity):
mozilla中关于优先级计算的代码(地址为http://hg.mozilla.org/mozilla-central/file/7297dedf2416/layout/style/stylerule.cpp(472行-537行)):
int32_t nscssselector::calcweightwithoutnegations() const { int32_t weight = 0; #ifdef moz_xul moz_assert(!(ispseudoelement() && pseudotype() != nscsspseudoelements::epseudo_xultree && mclasslist), if non-xul-tree pseudo-elements can have class selectors after them, specificity calculation must be updated); #else moz_assert(!(ispseudoelement() && mclasslist), if pseudo-elements can have class selectors after them, specificity calculation must be updated); #endif moz_assert(!(ispseudoelement() && (midlist || mattrlist)), if pseudo-elements can have id or attribute selectors after them, specificity calculation must be updated); if (nullptr != mcasedtag) { weight += 0x000001; } nsatomlist* list = midlist; while (nullptr != list) { weight += 0x010000; list = list->mnext; } list = mclasslist; #ifdef moz_xul // xul tree pseudo-elements abuse mclasslist to store some private // data; ignore that. if (pseudotype() == nscsspseudoelements::epseudo_xultree) { list = nullptr; } #endif while (nullptr != list) { weight += 0x000100; list = list->mnext; } // fixme (bug 561154): this is incorrect for :-moz-any(), which isn't // really a pseudo-class. in order to handle :-moz-any() correctly, // we need to compute specificity after we match, based on which // option we matched with (and thus also need to try the // highest-specificity options first). nspseudoclasslist *plist = mpseudoclasslist; while (nullptr != plist) { weight += 0x000100; plist = plist->mnext; } nsattrselector* attr = mattrlist; while (nullptr != attr) { weight += 0x000100; attr = attr->mnext; } return weight; } int32_t nscssselector::calcweight() const { // loop over this selector and all its negations. int32_t weight = 0; for (const nscssselector *n = this; n; n = n->mnegations) { weight += n->calcweightwithoutnegations(); } return weight; }
和webkit一样,inline style元素不计入计算。对于b级(id)、c级(class)、d级(tag)的最大值和最小值也都和webkit保持一致。不同的是在mozilla中并没有对于同一类别的选择器进行最大值控制,而是结果直接相加。这样的话就会导致同一级选择器数目多于255时高一级进一,也就是结果溢出的问题。而且对于整个选择器组的优先级计算因为没有类似于webkit的按位与运算来保证结果不溢出,只是简单的相加,在mozilla中就可能出现溢出的问题。
因为ie无法阅读代码,所以对于ie系列只能采取demo测试的方法来确认问题。在所有ie系列(q、s)中,表现都和mozilla一致。包括最新的ie11。
注:css选择器还有一个继承性:
js bin
test text
在所有浏览器中文字都会应用p {font-size:24px;}。如果把这句去掉的话,就会应用*{font-size:40px;},*包括p。(继承的样式没有优先级)
结论:1、优先级计算时跨级相加应注意溢出问题;
2、优先级计算不包括inline style和!important;
3、优先级计算只有同一类别才具有可比性(一般也不会有人定义超出255个的同一选择器)。
顺便引用stackoverflow上的一个回答来结束这篇文章:
i am currently using the book css mastery: advanced web standards solutions.
chapter 1, page 16 says:
to calculate how specific a rule is, each type of selector is assigned a numeric value. the specificity of a rule is then calculated by adding up the value of each of its selectors. unfortunately, specificity is not calculated in base 10 but a high, unspecified, base number. this is to ensure that a highly specific selector, such as an id selector, is never overridden by lots of less specific selectors, such as type selectors.
参考文章:http://trac.webkit.org/browser/trunk/source/webcore/css/cssselector.cpp
http://hg.mozilla.org/mozilla-central/file/17c65d32c7b8/layout/style/stylerule.cpp#l521
浏览器的工作原理:新式网络浏览器幕后揭秘
kb005: css 层叠