問題描述
在 CSS Lint 中,他們不建議使用 id
來選擇元素.我信任 CSS Lint,因?yàn)樗怯蓪?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 給出了他們?yōu)槭裁刺岢鼋ㄗh的指南:
CSSLint gives a guide to why they make their recommendations:
ID 不應(yīng)該在選擇器中使用,因?yàn)檫@些規(guī)則與 HTML 耦合太緊密,沒有重用的可能性.最好在選擇器中使用類,然后將類應(yīng)用于頁面中的元素.此外,ID 會(huì)影響您的特異性,并可能導(dǎo)致特異性戰(zhàn)爭.
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.)
基本上,如果您構(gòu)建代碼以使用類而不是 ID,您的代碼可以更通用且可重用,這通常是一件好事.此外,特異性是一件很難理解的事情,并且可能會(huì)導(dǎo)致難以發(fā)現(xiàn)的錯(cuò)誤,因此如果您省略 ID 選擇器,您就不太可能以意想不到的方式解決沖突的規(guī)則.
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.
這篇關(guān)于為什么在 CSS 中不建議按 ID 選擇?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!