CSS组合器优先级?

标签 css css-selectors

是否有像这样的组合器的优先级

a > b ~ c d

(注意cd之间的空格是后代组合子)

或者只是从左到右阅读,比如

((a > b) ~ c) d

?

最佳答案

不,组合器中没有优先级的概念。但是,复杂选择器中存在元素顺序的概念。

任何复杂的选择器都可以在任何对你有意义的方向上阅读,但这并不意味着组合器是distributive。或 commutative ,因为他们indicate a relationship between two elements ,例如祖先后代previous + next。这就是为什么元素的顺序很重要。

According to Google ,但是,浏览器实现了它们的选择器引擎,以便它们从右到左评估复杂的选择器:

The engine [Gecko] evaluates each rule from right to left, starting from the rightmost selector (called the "key") and moving through each selector until it finds a match or discards the rule.

Mozilla 的文章,Writing Efficient CSS for use in the Mozilla UI有一个部分描述了他们的 CSS 引擎如何评估选择器。这是特定于 XUL 的,但相同的布局引擎用于 Firefox 的 UI 和显示在 Firefox 视口(viewport)中的页面。 (死链接)

如谷歌在上述引文中所述,键选择器只是指最右边的简单选择器序列,所以它还是从右到左:

The style system matches rules by starting with the key selector, then moving to the left (looking for any ancestors in the rule’s selector). As long as the selector’s subtree continues to check out, the style system continues moving to the left until it either matches the rule, or abandons because of a mismatch.

请记住两件事:

  • 这些是根据实现细节记录的;从本质上讲,选择器就是一个选择器,它要做的就是匹配满足特定条件(由选择器的组件布局)的元素。从哪个方向读取取决于实现;正如另一个答案所指出的那样,the spec没有说明以何种顺序评估选择器或组合子优先级。

  • 这两篇文章都没有暗示每个简单选择器都是从左到右求值的在其简单选择器序列中(请参阅 this answer 为什么我认为这不是> 案例)。文章所说的是,浏览器引擎将评估键选择器序列以确定它的工作 DOM 元素是否匹配它,然后如果匹配,通过跟随组合器进入下一个选择器序列并且检查与该序列匹配的任何元素,然后冲洗并重复直到完成或失败。


综上所述,如果你要我阅读选择器并用简单的英语描述他们选择的内容,我也会从右到左阅读它们(但我不确定这是否与实现细节相关!)。

所以,选择器:

a > b ~ c d

意味着:

Select any d element
that is a descendant of a c element
that is a sibling of, and comes after, a b element
that is a child (direct descendant) of an a element.

关于CSS组合器优先级?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3851635/

相关文章:

html - 页面内容低于 div

html - Django 表单 - 禁用自定义 css 的错误转义

html - 使 div 占用剩余宽度

CSS 不同的字体大小 Windows/Linux/Mac

javascript - Jquery-从 <td> 内的输入获取值到数组中

xml - 在具有相同元素名称的一个 XML 上使用多个 CSS

CSS3 选择器问题

html - 如何给div添加边距

html - 如何在 WP 中隐藏除具有当前菜单祖先的元素之外的完整菜单

css - .container.\31 25\25 在 CSS 中是什么意思?