为什么在CSS中不推荐使用ID选择? [英] Why selecting by ID is not recommended in CSS?

查看:433
本文介绍了为什么在CSS中不推荐使用ID选择?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在CSSLint (csslint.net )中,他们不建议使用 id 用于选择元素。我相信CSS Lint,因为它是由聪明的人谁知道CSS非常好,深入。但我想知道原因是什么?为什么选择 id 不是好事?

In CSSLint (csslint.net), 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.

(link)

基本上,如果你的代码结构使用类而不是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选择?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆