css - 为什么我读到的 99% 的 CSS 布局代码都使用类而不是 ID?

标签 css

为什么这么多人对永远不会有多个实例的元素使用类?例如所有典型的布局元素,页眉、页脚、侧边栏等。

除了限制 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/

相关文章:

css - 使用 CSS 动画行文本

html - 使用 CSS 将禁用的选择居中对齐

javascript - 如何使 twitter bootstrap 子菜单在左侧打开?

javascript - Angular 2 将组件向后移动(更改 z 位置)

CSS Layers Z-Index IE8 兼容模式 - 下拉菜单

css - 使用负边距,如何重叠 div 并将其隐藏?

css - HTML/CSS 在 div 内水平对齐元素的最佳方法

css - 将 ul 粘贴到 div 的底部

javascript - Jquery - 在点击时切换默认隐藏的嵌套 div

javascript - 在 iFrame 中打开 CSS 文件时阻止浏览器提示文件下载?