在 CSS Lint 中,他们不建议使用 id
来选择元素.我信任 CSS Lint,因为它是由对 CSS 非常了解和深入的聪明人编写的.但我想知道这是什么原因?为什么用 id
选择不是一件好事?
In CSS Lint, they don't recommend using an id
for selecting elements. I trust CSS Lint because it written by smart people who know CSS very good and in depth. But I want to know what are reasons of this? Why is selecting with an id
not a good thing?
CSSLint 给出了他们为什么提出建议的指南:
CSSLint gives a guide to why they make their recommendations:
ID 不应该在选择器中使用,因为这些规则与 HTML 耦合太紧密,没有重用的可能性.最好在选择器中使用类,然后将类应用于页面中的元素.此外,ID 会影响您的特异性,并可能导致特异性战争.
IDs shouldn't be used in selectors because these rules are too tightly coupled with the HTML and have no possibility of reuse. It's much preferred to use classes in selectors and then apply a class to an element in the page. Additionally, IDs impact your specificity and can lead to specificity wars.
(来自 禁止选择器中的 ID.)
基本上,如果您构建代码以使用类而不是 ID,您的代码可以更通用且可重用,这通常是一件好事.此外,特异性是一件很难理解的事情,并且可能会导致难以发现的错误,因此如果您省略 ID 选择器,您就不太可能以意想不到的方式解决冲突的规则.
Basically, if you structure your code to use classes rather than IDs, your code can be more general and reusable, which is generally a good thing. Furthermore, specificity is a hard thing to get your head around, and can cause bugs that are hard to find, so if you omit ID selectors, you're less likely to have conflicting rules resolved in unexpected ways.
这篇关于为什么在 CSS 中不建议按 ID 选择?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!