无视速度和兼容性,为什么不只使用类,从不在HTML / CSS中使用ID?

时间:2022-01-23 08:47:11

I use only classes and never use IDs. Many people like to use IDs for different reasons.

我只使用类,从不使用ID。许多人喜欢出于不同的原因使用ID。

I've seen many questions regarding IDs vs classes on *, but no one addressed pure code organization point of view disregarding compatibility and runtime performance.

我在*上看到了很多关于ID和类的问题,但没有人解决纯代码组织的观点,无论兼容性和运行时性能如何。

From code organization point of view, I think that using IDs is bad just like using global variables in Visual Basic code.

从代码组织的角度来看,我认为使用ID就像在Visual Basic代码中使用全局变量一样糟糕。

One reason is that IDs have to be unique which introduces unnecessary and bad dependency between different independent parts of your code (controlling different parts of HTML DOM tree).

一个原因是ID必须是唯一的,这会在代码的不同独立部分之间引入不必要的和不良的依赖关系(控制HTML DOM树的不同部分)。

Another reason is that making new class names is actually easier than ID names because with IDs you have to worry about global scope and with class names you need to worry only about uniqueness in local scope, same benefit as with local variables.

另一个原因是创建新的类名实际上比ID名称更容易,因为使用ID您必须担心全局范围和类名,您只需要担心局部范围内的唯一性,与局部变量相同的好处。

Most people will argue that performance of addressing by ID is better than by class and I will agree with that. But as browsers become more advanced with native implementations of CSS addressing from javascript and computers become faster, performance becomes less and less important. So let's disregard it and concentrate only on organization of code in context of current question.

大多数人会争辩说ID的解决方式比同类的解决方案更好,我同意这一点。但随着浏览器变得越来越先进,javascript和计算机的CSS寻址的本机实现变得越来越快,性能变得越来越不重要。因此,让我们忽视它,只关注当前问题背景下的代码组织。

This discussion started here, but my potentially wrong advice generates negative points and became too big to keep in comments, so here I try to convert it into something positive and manageable.

这个讨论从这里开始,但我可能错误的建议会产生负面影响而且变得太大而无法保留评论,所以在这里我尝试将其转换为积极且易于管理的东西。

One visible point in favor of IDs is to use them as a tool of rule prioritization because priority of #name is higher than priority of .name. My response: using IDs to raise priorities is bad hack, it's cleaner and there is more freedom if you use additional root elements inserted between body and other levels of tree, for example priority of body div div span.class1{} is higher than body div span.class1{} is higher than body span.class1{} is higher than span.class1{}. Another tool to use for that purpose is !important. Some may argue that using more root elements means more difficulties when the page structure changes, but I don't think this is the case because you never have to put anything between body and designated for prioritization divs. Those divs can always stay below body and above all other content.

支持ID的一个可见点是将它们用作规则优先级的工具,因为#name的优先级高于.name的优先级。我的回答:使用ID来提高优先级是糟糕的黑客,它更清晰,如果你使用在主体和其他级别的树之间插入额外的根元素,有更多的*,例如body div div span.class1 {}的优先级高于body div span.class1 {}高于body span.class1 {}高于span.class1 {}。另一个用于此目的的工具是重要的。有些人可能会争辩说,当页面结构发生变化时,使用更多的根元素意味着更多的困难,但我不认为是这种情况,因为你永远不必在body之间放置任何东西并指定优先级div。这些div总是可以保持在身体之下,而不是其他所有内容。

Another interesting association was brought about pointers and that IDs are not bad because pointers are not bad. My response: pointers are bad if you hardcode absolute memory address in your code. Using relative pointers is always better (examples: using segments(CS,DS,SS,ES) in 8086 CPU; relative variable and method addresses generated by compilers). If we consider DOM tree as memory and compare using ID to using class then #name represents absolute memory address, but div.tab1 .name represents relative address (relative to div.tab1).

另一个有趣的关联带来了指针,ID也不错,因为指针也不错。我的回答:如果你在代码中对绝对内存地址进行硬编码,指针会很糟糕。使用相对指针总是更好(例如:在8086 CPU中使用段(CS,DS,SS,ES);由编译器生成的相对变量和方法地址)。如果我们将DOM树视为内存并使用ID与使用类进行比较,则#name表示绝对内存地址,但div.tab1 .name表示相对地址(相对于div.tab1)。

Another supporting point that I've seen for IDs is that elements with IDs are more easily available in javascript as becoming global properties. My response: again, this is like saying that global variables in Visual Basic are more conveniently available. The problem is that you can't keep large enough global (or any other) namespace in order without introducing naming hierarchy like level1_level2_name, which is just a hack to replace one namespace mechanism with another. DOM tree is convenient enough to organize namespaces, why disregard it ?

我在ID中看到的另一个支持点是,带有ID的元素在javascript中更容易成为全局属性。我的回答:再次,这就像说Visual Basic中的全局变量更方便。问题是你不能保持足够大的全局(或任何其他)命名空间,而不引入像level1_level2_name这样的命名层次结构,这只是将一个命名空间机制替换为另一个命名空间机制。 DOM树很方便组织命名空间,为什么要忽视呢?

Namespace simulation inside IDs using underscore is bad because you can't establish naming context and will have to duplicate all paths everywhere in your code. That practically means that you won't be able to use CSS preprocessors that fix inability of CSS to use contexts.

使用下划线在ID内部进行命名空间模拟是不好的,因为您无法建立命名上下文,并且必须复制代码中的所有路径。这实际上意味着您将无法使用CSS预处理器来修复CSS无法使用上下文。

7 个解决方案

#1


7  

I agree with you in general: Classes are much cleaner to use; you can create "namespaces" and clean cascades with them; and they can be combined: class='class1 class2'.

我总体上同意你的观点:使用类更清晰;你可以创建“命名空间”并用它们清理级联;它们可以合并:class ='class1 class2'。

IDs still have their place when you're addressing really unique elements on the page, especially when addressing an element that is going to be changed in JavaScript later (e.g. a hidden overlay.)

当您在页面上寻址真正独特的元素时,ID仍然具有它们的位置,尤其是在寻址稍后将在JavaScript中更改的元素时(例如隐藏的叠加层)。

#2


13  

quick answer: its a best practice, if you have only one instance of something and you only want one instance if it, use an ID to define that there should only be one instance of it.

快速回答:它是一种最佳实践,如果你只有一个实例,而你只想要一个实例,那么使用一个ID来定义它应该只有一个实例。

This is like the difference between constant variables vs regular variables. You can use a regular variable to be a constant variable, but its better to define it as such if that is what its intended to be.

这就像常量变量与常规变量之间的差异。您可以使用常规变量作为常量变量,但如果它是预期变量,则更好地定义它。

It lets fellow programmers (and yourself) know more information about the object.

它让其他程序员(和你自己)知道有关该对象的更多信息。

#3


4  

I look at classes and ids the same way I look at a (programming) class versus an object. An object is one, specific instance of a class. I want all my classes to share a certain number of behaviors, but an individual object may have its own unique properties. CSS classes are for applying properties to broad groups of similar items, ids are for specific items and the specificity hierarchy reflects that.

我看一下类和id,就像我看一个(编程)类和一个对象一样。对象是类的一个特定实例。我希望我的所有类共享一定数量的行为,但单个对象可能有自己独特的属性。 CSS类用于将属性应用于广泛的类似项目组,ID用于特定项目,特殊性层次结构反映了这一点。

To invert your question, why use classes at all when you could achieve the same effects with very specific tag selectors? For ease of use, repeatability and clarity of intent.

要反转您的问题,为什么在使用非常特定的标签选择器实现相同的效果时,根本使用类?易于使用,重复性和意图清晰度。

#4


2  

For me, I like using IDs on HTML elements that are absolutely unique, and classes on things that are possibly non-unique (regardless of whether or not they are).

对我来说,我喜欢在HTML元素上使用绝对唯一的ID,以及可能不是唯一的东西的类(无论它们是否是)。

For example, I would use <div id="header"> because there can only be one header. But I would use <div class="profile"> if there could conceivably be more than one on the page (even if there is only one). This makes the CSS a little easier for me to understand.

例如,我会使用

因为只能有一个标题。但是我会使用
如果可能在页面上有多个(即使只有一个)。这使我更容易理解CSS。

#5


1  

"DOM tree is convenient enough to organize namespaces, why disregard it ?"

“DOM树很方便组织命名空间,为什么要忽视它呢?”

Because the DOM can change due to AJAX or other javascripty-goodness.

因为DOM可以因AJAX或其他javascripty-goodness而改变。

I like @ocdcoder 's constant/variable analogy. Sometimes you want to refer to exactly that particular element. Having to adhere to a strict DOM namespace is a straightjacket that doesn't help maintenance at all, imho.

我喜欢@ocdcoder的常数/变量类比。有时您想要完全引用该特定元素。不得不遵守一个严格的DOM名称空间是一件根本无法维护的紧身衣,imho。

#6


1  

I think the discussion is incomplete without addressing the underlying reason for using classes and IDs. Saying that either should be used in every situation does not work well generally and historically.

我认为如果不解决使用类和ID的根本原因,讨论是不完整的。在任何情况下都应该使用这两种方法在一般和历史上都不能很好地发挥作用。

The original purpose of classes was to attach presentation to the document, or introduce style as a separate concern than the structure of the document itself. Please correct me if I am wrong, but I think you are trying to address the problem of attaching semantic information to the elements rather than just style. If that is indeed the case, then classes serve two purposes for us - controlling presentation, and acting and semantic tags. IDs serve the purpose of acting as a unique semantic tag.

类的最初目的是将演示文稿附加到文档,或者将样式作为单独的关注点而不是文档本身的结构。如果我错了,请纠正我,但我认为你正在努力解决将语义信息附加到元素而不仅仅是样式的问题。如果确实如此,那么类为我们服务于两个目的 - 控制表示,表演和语义标签。 ID用作充当唯一语义标记的目的。

XML is highly extensible and allows namespaces which was supposed to be used in XHTML documents to assign meaning to a document as authors saw fit. But there were none in HTML and maybe it was browser incompatibilities or the non ease of use (as Tom mentioned), but most web pages and applications did not take the path of using namespaces in XHTML.

XML具有高度可扩展性,允许在XHTML文档中使用的命名空间为作者认为合适的文档赋予意义。但HTML中没有,可能是浏览器不兼容或不易使用(如Tom所提到的),但大多数网页和应用程序都没有采用在XHTML中使用命名空间的路径。

Surely the HTML spec authors saw the glaring need for attaching semantic data to HTML documents and introduced the data- attributes in HTML5 that could be assigned to any element. I would argue that if it's semantic meaning that you are concerned with, this is absolutely the best approach so far, but again browser incompatibilities have always had a major role in determining which spec becomes more commonplace and I hope IE does not have their say this time.

当然,HTML规范作者看到了将语义数据附加到HTML文档以及在HTML5中引入可分配给任何元素的数据属性的明显需求。我认为,如果它是你所关注的语义,这绝对是迄今为止最好的方法,但是浏览器不兼容性总是在确定哪个规范变得更加普遍时起主要作用,我希望IE没有他们的发言权时间。

#7


1  

Using an id attribute allows you to link to an element E.g. if you’ve got this HTML:

使用id属性可以链接到元素E.g.如果你有这个HTML:

<div id="log-in">

you can link to the log in section of the page using href="#log-in".

您可以使用href =“#log-in”链接到页面的登录部分。

You’re quite right that classes are usually the most convenient and appropriate way to identify page components. But assuming that you’ve got an element that only appears once per page, and assuming you can give it an appropriate name or generate one, I don’t think you’re likely to run into problems using an id for it.

你是对的,类通常是识别页面组件的最方便和最合适的方法。但假设你有一个每页只出现一次的元素,并假设你可以给它一个合适的名字或生成一个,我认为你可能会遇到使用id的问题。

#1


7  

I agree with you in general: Classes are much cleaner to use; you can create "namespaces" and clean cascades with them; and they can be combined: class='class1 class2'.

我总体上同意你的观点:使用类更清晰;你可以创建“命名空间”并用它们清理级联;它们可以合并:class ='class1 class2'。

IDs still have their place when you're addressing really unique elements on the page, especially when addressing an element that is going to be changed in JavaScript later (e.g. a hidden overlay.)

当您在页面上寻址真正独特的元素时,ID仍然具有它们的位置,尤其是在寻址稍后将在JavaScript中更改的元素时(例如隐藏的叠加层)。

#2


13  

quick answer: its a best practice, if you have only one instance of something and you only want one instance if it, use an ID to define that there should only be one instance of it.

快速回答:它是一种最佳实践,如果你只有一个实例,而你只想要一个实例,那么使用一个ID来定义它应该只有一个实例。

This is like the difference between constant variables vs regular variables. You can use a regular variable to be a constant variable, but its better to define it as such if that is what its intended to be.

这就像常量变量与常规变量之间的差异。您可以使用常规变量作为常量变量,但如果它是预期变量,则更好地定义它。

It lets fellow programmers (and yourself) know more information about the object.

它让其他程序员(和你自己)知道有关该对象的更多信息。

#3


4  

I look at classes and ids the same way I look at a (programming) class versus an object. An object is one, specific instance of a class. I want all my classes to share a certain number of behaviors, but an individual object may have its own unique properties. CSS classes are for applying properties to broad groups of similar items, ids are for specific items and the specificity hierarchy reflects that.

我看一下类和id,就像我看一个(编程)类和一个对象一样。对象是类的一个特定实例。我希望我的所有类共享一定数量的行为,但单个对象可能有自己独特的属性。 CSS类用于将属性应用于广泛的类似项目组,ID用于特定项目,特殊性层次结构反映了这一点。

To invert your question, why use classes at all when you could achieve the same effects with very specific tag selectors? For ease of use, repeatability and clarity of intent.

要反转您的问题,为什么在使用非常特定的标签选择器实现相同的效果时,根本使用类?易于使用,重复性和意图清晰度。

#4


2  

For me, I like using IDs on HTML elements that are absolutely unique, and classes on things that are possibly non-unique (regardless of whether or not they are).

对我来说,我喜欢在HTML元素上使用绝对唯一的ID,以及可能不是唯一的东西的类(无论它们是否是)。

For example, I would use <div id="header"> because there can only be one header. But I would use <div class="profile"> if there could conceivably be more than one on the page (even if there is only one). This makes the CSS a little easier for me to understand.

例如,我会使用

因为只能有一个标题。但是我会使用
如果可能在页面上有多个(即使只有一个)。这使我更容易理解CSS。

#5


1  

"DOM tree is convenient enough to organize namespaces, why disregard it ?"

“DOM树很方便组织命名空间,为什么要忽视它呢?”

Because the DOM can change due to AJAX or other javascripty-goodness.

因为DOM可以因AJAX或其他javascripty-goodness而改变。

I like @ocdcoder 's constant/variable analogy. Sometimes you want to refer to exactly that particular element. Having to adhere to a strict DOM namespace is a straightjacket that doesn't help maintenance at all, imho.

我喜欢@ocdcoder的常数/变量类比。有时您想要完全引用该特定元素。不得不遵守一个严格的DOM名称空间是一件根本无法维护的紧身衣,imho。

#6


1  

I think the discussion is incomplete without addressing the underlying reason for using classes and IDs. Saying that either should be used in every situation does not work well generally and historically.

我认为如果不解决使用类和ID的根本原因,讨论是不完整的。在任何情况下都应该使用这两种方法在一般和历史上都不能很好地发挥作用。

The original purpose of classes was to attach presentation to the document, or introduce style as a separate concern than the structure of the document itself. Please correct me if I am wrong, but I think you are trying to address the problem of attaching semantic information to the elements rather than just style. If that is indeed the case, then classes serve two purposes for us - controlling presentation, and acting and semantic tags. IDs serve the purpose of acting as a unique semantic tag.

类的最初目的是将演示文稿附加到文档,或者将样式作为单独的关注点而不是文档本身的结构。如果我错了,请纠正我,但我认为你正在努力解决将语义信息附加到元素而不仅仅是样式的问题。如果确实如此,那么类为我们服务于两个目的 - 控制表示,表演和语义标签。 ID用作充当唯一语义标记的目的。

XML is highly extensible and allows namespaces which was supposed to be used in XHTML documents to assign meaning to a document as authors saw fit. But there were none in HTML and maybe it was browser incompatibilities or the non ease of use (as Tom mentioned), but most web pages and applications did not take the path of using namespaces in XHTML.

XML具有高度可扩展性,允许在XHTML文档中使用的命名空间为作者认为合适的文档赋予意义。但HTML中没有,可能是浏览器不兼容或不易使用(如Tom所提到的),但大多数网页和应用程序都没有采用在XHTML中使用命名空间的路径。

Surely the HTML spec authors saw the glaring need for attaching semantic data to HTML documents and introduced the data- attributes in HTML5 that could be assigned to any element. I would argue that if it's semantic meaning that you are concerned with, this is absolutely the best approach so far, but again browser incompatibilities have always had a major role in determining which spec becomes more commonplace and I hope IE does not have their say this time.

当然,HTML规范作者看到了将语义数据附加到HTML文档以及在HTML5中引入可分配给任何元素的数据属性的明显需求。我认为,如果它是你所关注的语义,这绝对是迄今为止最好的方法,但是浏览器不兼容性总是在确定哪个规范变得更加普遍时起主要作用,我希望IE没有他们的发言权时间。

#7


1  

Using an id attribute allows you to link to an element E.g. if you’ve got this HTML:

使用id属性可以链接到元素E.g.如果你有这个HTML:

<div id="log-in">

you can link to the log in section of the page using href="#log-in".

您可以使用href =“#log-in”链接到页面的登录部分。

You’re quite right that classes are usually the most convenient and appropriate way to identify page components. But assuming that you’ve got an element that only appears once per page, and assuming you can give it an appropriate name or generate one, I don’t think you’re likely to run into problems using an id for it.

你是对的,类通常是识别页面组件的最方便和最合适的方法。但假设你有一个每页只出现一次的元素,并假设你可以给它一个合适的名字或生成一个,我认为你可能会遇到使用id的问题。