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:12

If you are using .Net web controls then it is sometimes a lot easier just to use classes as .Net alters web contol div id's at run time (where they are using runat="server").

Using classes allows you to easily build up styles with separate classes for fonts, spacing, borders etc. I generally use multiple files to store separate types of formatting information, e.g. basic_styles.css for simple site wide formatting, ie6_styles.css for browser specific styles (in this case IE6) etc and template_1.css for layout information.

Which ever way you choose try to be consistent to aid maintenance.

查看更多
何处买醉
3楼-- · 2019-01-02 16:13

An additional benefit to using an ID is the ability to target it in an anchor tag:

<h2 id="CurrentSale">Product I'm selling</h2>

Will allow you to in some other place link directly to that spot on the page:

<a href="#CurrentSale">the Current Sale</a>

A common use for this would be to give each headline on a blog a datestamped ID (say id="date20080408") which would allow you to specifically target that section of the blog page.

It is also important to remember that there are more restricted naming rules for ids, primarily that they can't start with a number. See similar SO question: What is a valid value for id attributes in html

查看更多
无色无味的生活
4楼-- · 2019-01-02 16:14

classes are great when you want to apply similar styles to many different divs or elements. ids are good when you want to address a specific element for formatting or for updating with javascript.

查看更多
孤独总比滥情好
5楼-- · 2019-01-02 16:14

id is supposed to be the element unique identifier on the page, which helps to manipulate it. Any externally CSS defined style that is supposed to be used in more than one element should go on the class attribute

<div class="code-formatting-style-name" id="myfirstDivForCode">
</div>
查看更多
临风纵饮
6楼-- · 2019-01-02 16:16

Use id to identify elements that there will only be a single instance of on a page. For instance, if you have a single navigation bar that you are placing in a specific location, use id="navigation".

Use class to group elements that all behave a certain way. For instance, if you want your company name to appear in bold in body text, you might use <span class='company'>.

查看更多
何处买醉
7楼-- · 2019-01-02 16:16

IDs must be unique but in CSS they also take priority when figuring out which of two conflicting instructions to follow.

<div id="section" class="section">Text</div>
#section {font-color:#fff}
.section {font-color:#000}

The text would be white.

查看更多
登录 后发表回答