html - CSS类和id之间的处理速度差异

标签 html css dom css-selectors

对于这个问题,我只比较了浏览器在 2 个元素上渲染 CSS 的速度,这两个元素的不同之处仅在于一个有类,一个有 id。

(这里与JS识别、anchor使用等无关)

<div class="myclass">classed element</div>
<div id="myid">ided element</div>

有人对此有数字吗?我读到过 CSS id“更快”,但究竟快多少呢?我会冒险猜测它可以忽略不计,但知道它会很有趣。

最佳答案

https://web.archive.org/web/20190901050026/http://oli.jp/2011/ids/

ID 的在某些情况下更快,但不是全部

It’s a common belief that ID selectors are the fastest, but this comes with a big caveat: IDs are fastest CSS selector only if they’re the key selector. What’s that? Well, while you probably read selectors from left to right, browsers read them from right to left.

此处还有针对您的号码请求的性能测试:https://web.archive.org/web/20190901050026/http://oli.jp/2011/ids/#table1

结论

ID 的正确使用速度更快,但与类别的差异如此之小 - 不值得任何考虑。

It seems to me that there are no convincing reasons to use IDs in selectors for CSS styling¹, as CSS classes can do everything IDs can. Hopefully you’ll agree there are some good reasons not to. Think about it the next time you start a personal project or redesign your own site, and try adding a class (or ARIA landmark roles) for styling instead. Save IDs for fragment identifiers or JavaScript hooks

关于html - CSS类和id之间的处理速度差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31026901/

相关文章:

javascript - Jquery Toggle Menu 和 Jquery Show and Hide with rollover

html - 内联 block div 内的内联元素

jquery - 使用 jQuery slideToggle 扩展 Div

html - 模态框打不开

html - CSS:绝对元素中的绝对元素

html - div居中的定位问题

javascript - 使用这个经过 CSS 转换的翻盖卡片,我怎样才能让背面的内容易于访问?

javascript - 具有隔离范围的 Angularjs 指令不会触发指令之外的 DOM 更改

jquery - 如何在 jQuery 中将两个标签合并在一起?

javascript - jsPDF/jsPDF-autotable 将 dom 元素打印到表格中