CSS类和id之间的处理速度差异 [英] processing speed difference between CSS class and id

查看:68
本文介绍了CSS类和id之间的处理速度差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于这个问题,我只是比较浏览器在两个元素上呈现CSS的速度,这些元素的不同之处仅在于一个元素具有一个类,一个元素具有一个id.

For this question, I'm only comparing a browser's speed in rendering the CSS on 2 elements which are different only in that one has a class and one has an id.

(这与JS标识,锚点使用等无关)

(This has nothing to do with JS identification, anchor use, etc.)

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

有人对此有数字吗?我已经读过CSS id可以更快",但是要多少呢?我要冒险猜测它可以忽略不计,但是知道这将很有趣.

Does anyone have numbers on this? I have read that CSS ids are 'faster,' but by how much? I'm going to hazard a guess that it's negligible, but it would be interesting to know.

推荐答案

http://oli.jp/2011/ids/

ID的 在某些情况下更快,但并非全部

ID's are faster in some cases, but not all

人们普遍认为ID选择器是最快的,但这带来了一个很大的警告:ID仅在是键选择器时才是最快的CSS选择器.那是什么?好吧,虽然您可能是从左到右读取选择器,但浏览器还是从右到左读取它们.

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.

这里还针对您的电话号码请求进行了性能测试: http://oli.jp/2011/ids/#table1

There's also a performance test here for your numbers request: http://oli.jp/2011/ids/#table1

结论

正确使用ID的速度更快,但与类之间的差异却很小-无需任何考虑.

ID's used correctly are faster, but with such a minimal difference vs classes - it's not worth any consideration.

在我看来,没有令人信服的理由在CSS样式选择器中使用ID,因为CSS类可以完成ID所能做的一切.希望您会同意有一些充分的理由不这样做.下次启动个人项目或重新设计自己的站点时,请考虑一下,然后尝试添加类(或ARIA标志性角色)来进行样式设置.保存用于片段标识符或JavaScript钩子的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

这篇关于CSS类和id之间的处理速度差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆