您的位置首页百科问答

CSS 的 ID 和 Class 有什么区别?如何正确使用它们?

CSS 的 ID 和 Class 有什么区别?如何正确使用它们?

的有关信息介绍如下:

CSS 的 ID 和 Class 有什么区别?如何正确使用它们?

---------- update 2016.10.19 --------

看了下大部分答案,发现大家(包括我)都忽略了一个最重要的点,那就是 id 作为 unique identifier 究竟是怎么定义的,最新的 html5 spec 中这样写道:

也就是说,id 通常应该由纯数字组成,且不应该包含特别的含义。

--------- 以下是原回答 -----------

这种问题还得看标准怎么描述的:

id:The

attribute specifies its element's

.

class:There are no additional restrictions on the tokens authors can use in the

attribute, but authors are encouraged to use values that describe the nature of the content, rather than values that describe the desired presentation of the content.

简言之就是,id是身份证应用中唯一。class是类别标识,表明当前元素属于哪一类。关于用法上,最容易误用的就是class,按照w3c的描述,class应该是描述内容的本质(语义)的而不是内容长什么样的,也就是说,你不应该写非语义化的class。典型的反面教材就是 class="fl mr10" 之流。

知乎上贺老早前就答过几次这类问题,可以去搜一下。嫌麻烦的也可以看看我整理的这篇