CSS 性能 : descendent or two direct descendent selectors best?

标签 css performance css-selectors

给定以下 HTML:

<ul>
  <li>
    <a ...

对于同一组声明,考虑到它们的性能,这两个规则集中的哪一个更可取?

ul > li > a {
  color: black
}
ul a {
  color: black
}

最佳答案

The most fundamental concept to learn is this rule filtering. The categories exist in order to filter out irrelevant rules (so the style system doesn’t waste time trying to match them).

For example, if an element has an ID, then only ID rules that match the element’s ID will be checked. Only Class Rules for a class found on the element will be checked. Only tag rules that match the tag will be checked. Universal Rules will always be checked.

避免后代选择器

The descendant selector is a more expensive selector than a child selector

BAD(后代选择器)
每当“ul”元素中的任何位置出现“a”时,将文本颜色设置为黑色

 ul a {
  color: black
}

比上面更好(子选择器)
“a”元素必须是“li”元素的子元素; “li”元素必须是“ul”元素的子元素

 ul > li > a {
  color: black
}

进一步阅读 LINK

关于CSS 性能 : descendent or two direct descendent selectors best?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29761324/

相关文章:

java - 为什么这两种算法的运行时间存在差异?

r - 在 R/Rcpp 中转置列表的最快方法

javascript - 将 JavaScript 迁移到 TypeScript

CSS 父亲选择器

javascript - 如何使用 jquery 将 css 应用于 catch 语句中的 div

IE8 中的 CSS 空白属性

C++ 性能 : checking a block of memory for having specific values in specific cells

javascript - CMS中不同类等高的jquery解决方案

javascript - 当图像宽度与视口(viewport)宽度不成比例时响应图像?

html - 当另一个子 div 悬停时更改子 div 的外观