当您特定时,CSS 会更快吗?

2022-01-10 00:00:00 css-selectors performance css

div.container 比 .container 快吗?你知道在 jquery 中,如果你更具体地使用你的选择器,它会更快,因为它迭代更少.. css 是这种情况吗?

Is div.container faster than .container ? You know like in jquery if you be more specific with your selectors it is faster since it iterates through less.. Is this the case with css ?

有没有办法衡量 css 的性能?性能方面,这样的事情是否重要,或者它基本上都取决于文本重量?

Is there a way to measure performance in css ? Performance wise, does things like this even matter or does it all depend on text weight basically ?

如果有人知道答案,我会很高兴,我实际上发现了一个没有确定答案的类似问题.如果指定得更好,CSS会更高效吗?

I'd be happy if someone knows the answer to it, I've actually found a similar question with no certain answer. Can CSS be more efficient if it is better specified?

推荐答案

在现实世界中,速度差异可以忽略不计.
技术方面的 .container 会更快,因为它需要处理的选择器更少.

In real world the speed difference would be negligible.
To be technical .container would be faster as it has fewer selectors to process.

选择器具有固有的效率.CSS 选择器从高到低的顺序是这样的:

Selectors have an inherent efficiency. The order of more to less efficient CSS selectors goes thus:

  1. ID,例如#header
  2. 类,例如.promo
  3. 类型,例如div
  4. 相邻的兄弟,例如h2 + p
  5. 孩子,例如李>ul
  6. 后裔,*例​​如ul a*
  7. 通用,即*
  8. 属性,例如[type="text"]
  9. 伪类/元素,例如a:hover

关于你的第二个问题:

有没有办法衡量 CSS 的性能?

Is there a way to measure performance in CSS ?

Steve Souders 推出了一项在线测试来衡量 CSS 的性能,仍然可以在此处访问该测试.

Steve Souders put out an online test to measure performance of CSS that can still be accessed here.

现在有更好的方法来衡量性能,但这是一种快速简便的资源,您可以使用.

There are better ways to measure performance nowadays, but this is a quick and easy resource you can play with.

在性能方面,这样的事情是否重要,或者它基本上都取决于文本重量?

Performance wise, does things like this even matter or does it all depend on text weight basically ?

简短的回答是不是真的".

The short answer is "not really".

答案很长,视情况而定".如果你在一个简单的网站上工作,除了一般知识之外,你真的没有必要对 CSS 性能大惊小怪,你可以从最佳实践中获得.

The long answer is, "it depends". If you are working on a simple site there is really no point to make a fuss about CSS performance other than general knowledge you may gain from best practices.

如果您要创建一个包含数万个 DOM 元素的网站,那么是的,这很重要.

If you are creating a site with tens of thousands of DOM elements then yes, it will matter.

相关文章