在CSS中,什么时候应该使用id,什么时候应该使用类?(复制)

时间:2022-11-20 21:20:06

Possible Duplicate:
CSS Best Practice about ID and Class?

可能的重复:CSS最佳实践关于ID和类?

To me, it seems like both achieve the same thing. So are there any rules or standards as to when ids are more appropriate over classes and vice versa.

对我来说,似乎两者都实现了同样的目标。因此,当ids在类上更合适时,是否有任何规则或标准,反之亦然。

I know this question may be seen as subjective, I don't have any preference over one or the other and am not trying to peddle anything here. I am genuinely curious as I am new to front end web development and would like to know which to use and when.

我知道这个问题可能被认为是主观的,我对其中一个或另一个没有任何偏好,我也不想在这里兜售任何东西。我真的很好奇,因为我刚接触到前端web开发,我想知道什么时候使用什么。

3 个解决方案

#1


3  

CSS Best Practice about ID and Class?

关于ID和类的CSS最佳实践?

#2


1  

When you need give multiple things an attribute/style, use a class, if it's singular, use an ID. If it's something I want to readily identify, like LoginBtn then it's an ID, if it's a style, like say an anchor that's blueLink, it's a class.

当你需要给多个东西一个属性/样式时,使用一个类,如果它是单数,就使用一个ID,如果它是我想很容易识别的东西,比如LoginBtn,那么它就是一个ID,如果它是一个样式,比如一个锚点blueLink,它就是一个类。

Another consideration for a lot of developers is javascript. e.g. a jQuery selector $('#id') is much faster than $('.class'), so if you're only dealing with one element, this is also an advantage.

许多开发人员需要考虑的另一个问题是javascript。例如,jQuery选择器$('#id')比$('.class')快得多,所以如果只处理一个元素,这也是一个优点。

#3


0  

This is not subjective. Classes can be used to give the two separate entities in the html (such as two divs) the same styling. Id's are unique and therefore can only style 1 element at a time.

这不是主观的。可以使用类为html中的两个独立实体(例如两个div)提供相同的样式。Id是唯一的,因此一次只能样式化一个元素。

edit: clarification

编辑:澄清

#1


3  

CSS Best Practice about ID and Class?

关于ID和类的CSS最佳实践?

#2


1  

When you need give multiple things an attribute/style, use a class, if it's singular, use an ID. If it's something I want to readily identify, like LoginBtn then it's an ID, if it's a style, like say an anchor that's blueLink, it's a class.

当你需要给多个东西一个属性/样式时,使用一个类,如果它是单数,就使用一个ID,如果它是我想很容易识别的东西,比如LoginBtn,那么它就是一个ID,如果它是一个样式,比如一个锚点blueLink,它就是一个类。

Another consideration for a lot of developers is javascript. e.g. a jQuery selector $('#id') is much faster than $('.class'), so if you're only dealing with one element, this is also an advantage.

许多开发人员需要考虑的另一个问题是javascript。例如,jQuery选择器$('#id')比$('.class')快得多,所以如果只处理一个元素,这也是一个优点。

#3


0  

This is not subjective. Classes can be used to give the two separate entities in the html (such as two divs) the same styling. Id's are unique and therefore can only style 1 element at a time.

这不是主观的。可以使用类为html中的两个独立实体(例如两个div)提供相同的样式。Id是唯一的,因此一次只能样式化一个元素。

edit: clarification

编辑:澄清