为什么这么多人对永远不会有多个实例的元素使用类?例如所有典型的布局元素,页眉、页脚、侧边栏等。
除了限制 ID 必须唯一标识页面上的元素之外,它们在所有方面都比类更好吗?渲染速度更快、javascript、更高的特异性等?我觉得我一定错过了一些东西,但我无法弄清楚。
最佳答案
这更多地取决于调用的复杂性,然后取决于 id 与选择器,请参阅 google docs 。
As the browser parses HTML, it constructs an internal document tree representing all the elements to be displayed. It then matches elements to styles specified in various stylesheets, according to the standard CSS cascade, inheritance, and ordering rules. In Mozilla's implementation (and probably others as well), for each element, the CSS engine searches through style rules to find a match. The engine 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. (The "selector" is the document element to which the rule should apply.)
所以它不需要搜索 DOM 来应用样式,实际上相反的情况发生。在构建 DOM 时,正在搜索样式表以查找匹配项。如果上述情况成立,则类的渲染速度将与 id 相同。
关于css - 为什么我读到的 99% 的 CSS 布局代码都使用类而不是 ID?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8492069/