問題描述
在 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模板網!