给定以下 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/