为什么在 CSS 中不建议按 ID 选择?

时间:2022-11-30
本文介绍了为什么在 CSS 中不建议按 ID 选择?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 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 选择?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!

上一篇:css :nth-child() :after 下一篇:在 Chrome 中嵌套 nth-child 的 querySelector 似乎不起作

相关文章

最新文章