div class vs id

2019-01-02 15:53发布

When using divs when is it best to use a class vs id?

Is it best to use class, on say font variant or elements within the html? Then use id for the structure/containers?

This is something I've always been a little uncertain on, any help would be great.

标签: css class xhtml
22条回答
余生无你
2楼-- · 2019-01-02 16:16

The HTML standard itself answers your question:

No two objects may have the same ID, but an arbitrarily amount of objects may have the same class.

So if you want to apply certain CSS style attributes to a single DIV only, that would be an ID. If you want certain style attributes to apply to multiple DIVs, that must be a class.

Note that you can mix both. You can make two DIVs belong to the same class, but give them different IDs. You can then apply the style common to both to the class, and the things specific to either one to their ID. The browser will first apply the class style and then the ID style, so ID styles can overwrite whatever a class has set before.

查看更多
时光乱了年华
3楼-- · 2019-01-02 16:16

Use an id for a unique element on the page which you want to do something very specific with, and a class for something which you could reuse on other parts of the page.

查看更多
时光乱了年华
4楼-- · 2019-01-02 16:16

In addition to id's and classes being great for setting style on an individual item verses a similar set of items, there's also another caveat to remember. It also depends on the language to some degree. In ASP.Net, you can throw in Div's and have id's. But, if you use a Panel instead of the Div you will lose the id.

查看更多
刘海飞了
5楼-- · 2019-01-02 16:22

The id attribute is used for elements to uniquely identify them within the document, whereas the class attribute can have the same value shared by many elements in the same document.

So, really, if there's only one element per document that's going to use the style (e.g., #title), then go with id. If multiple elements can use the style, go with class.

查看更多
登录 后发表回答