CSS: are class and id interchangeable?

2019-03-04 16:09发布

I know others have asked about using class and id in CSS files, such as

Div: Class vs Id

So I'm aware of the semantic and syntactic differences between class and id: that id should be used for elements that are used only once and class should be used for elements that share attributes in common.

But this isn't a hard-and-fast rule, is it? What's the harm in using an id for more than one element? Or using a class for only one? After all, isn't "one element" just a set (class) with only one thing in it?

Will the browser's CSS interpreter throw an error if I break the rules? I haven't seen it happen.

So why do we have both id and class? Why not just one one or the other and call it good?

标签: css class
7条回答
Ridiculous、
2楼-- · 2019-03-04 17:06

CSS won't complain if you do it but Javascript sure will if you want to grab one element by its id.

The real answer is that there is a semantic difference between an identifier for one and only one object and an identifier that can apply to multiple objects. While you can break the rules it is best not to.

There is also one other distinction between the two, an (X)HTML element allows more than one class to be applied like this:

<div class="foo bar"></div>

You can't do that with ids.

查看更多
登录 后发表回答