有什么区别?可以使用
吗?我看到不同的开发人员以两种方式这样做,而且由于我是自学成才的,所以我从来没有真正弄清楚。" />
有什么区别?可以使用
吗?我看到不同的开发人员以两种方式这样做,而且由于我是自学成才的,所以我从来没有真正弄清楚。">
有什么区别?可以使用
吗?我看到不同的开发人员以两种方式这样做,而且由于我是自学成才的,所以我从来没有真正弄清楚。" />
ChatGPT解决这个技术问题 Extra ChatGPT

What's the difference between an id and a class?

What's the difference between <div class=""> and <div id=""> when it comes to CSS? Is it alright to use <div id="">?

I see different developers doing this in both ways, and since I'm self taught, I've never really figured it out.


2
2 revs, 2 users 94%

ids must be unique where as class can be applied to many things. In CSS, ids look like #elementID and class elements look like .someClass

In general, use id whenever you want to refer to a specific element and class when you have a number of things that are all alike. For instance, common id elements are things like header, footer, sidebar. Common class elements are things like highlight or external-link.

It's a good idea to read up on the cascade and understand the precedence assigned to various selectors: http://www.w3.org/TR/CSS2/cascade.html

The most basic precedence you should understand, however, is that id selectors take precedence over class selectors. If you had this:

<p id="intro" class="foo">Hello!</p>

and:

#intro { color: red }
.foo { color: blue }

The text would be red because the id selector takes precedence over the class selector.


The reason, for those who care, that #intro has precedence is because of something called specificity: w3.org/TR/CSS2/cascade.html#specificity
TBH, nobody use id any more unless it has something to do with integration with JavaScript (when you need an unique value). It is html leftover and you do not need to use it just because it exists. Saying that you have only one header and such so you need id instead of class might be correct. But let's say you have a search bar with style properties. If you wanted to add another search bar with the same properties in the end of page later too you couldn't, because id can only be used one once. Honestly, I just don't see any use of id. It doesn't make your code more organised or anything.
Just confused these two things for quite a long time. Now I understood that "id" should be referred with unique element while "class" can be applied into multiple elements or things according their difference
I prefer to see ID in this way: if you have many elements which are alike (e.g. <li>in an <ul>) and you want to have a single one of them to behave different (whether CSS or JS doesn't matter), then you use id attribute.
ID is an identifier, CLASS is a list of styling rules, They exist for different purposes
S
Sampson

Perhaps an analogy will help understanding the difference:

<student id="JonathanSampson" class="Biology Calculus" />
<student id="MarySmith" class="Biology Networking" />

Student ID cards are distinct. No two students on campus will have the same student ID card. However, many students can and will share at least one Class with each other.

It's okay to put multiple students under one Class title, such as Biology. But it's never acceptable to put multiple students under one student ID.

When giving Rules over the school intercom system, you can give Rules to a Class:

"Tomorrow, all students are to wear a red shirt to Biology class."

.Biology {
  color: red;
}

Or you can give rules to a Specific Student, by calling his unique ID:

"Jonathan Sampson is to wear a green shirt tomorrow."

#JonathanSampson {
  color: green;
}

In this case, Jonathan Sampson is receiving two commands: one as a student in the Biology class, and another as a direct requirement. Because Jonathan was told directly, via the id attribute, to wear a green shirt, he will disregard the earlier request to wear a red shirt.

The more specific selectors win.


Can be confusing. You can't have on the same page <student id="JonathanSampson" class="Physics" />
@LucM why not? <div id="SomeId" class="SomeClass"></div> is perfectly valid
@Basic id must be uniq on a page. You can't have <student id="JonathanSampson" class="Biology" /> and <student id="JonathanSampson" class="Physics" />
@LucM I misunderstood your point - quite right, the id has to be unique, but you could do <student id="JonathanSampson" class="Biology Physics" />
K
Konstantin Tarkus

Where to use an ID versus a class

The simple difference between the two is that while a class can be used repeatedly on a page, an ID must only be used once per page. Therefore, it is appropriate to use an ID on the div element that is marking up the main content on the page, as there will only be one main content section. In contrast, you must use a class to set up alternating row colors on a table, as they are by definition going to be used more than once.

IDs are an incredibly powerful tool. An element with an ID can be the target of a piece of JavaScript that manipulates the element or its contents in some way. The ID attribute can be used as the target of an internal link, replacing anchor tags with name attributes. Finally, if you make your IDs clear and logical, they can serve as a sort of “self documentation” within the document. For example, you do not necessarily need to add a comment before a block stating that a block of code will contain the main content if the opening tag of the block has an ID of, say, "main", "header", "footer", etc.


L
Luc M

An id must be unique in the whole page.

A class may apply to many elements.

Sometimes, it's a good idea to use ids.

In a page, you usually have one footer, one header...

Then the footer may be into a div with an id

c
cletus

IDs are unique. Classes aren't. Elements can also have multiple classes. Also classes can be dynamically added and removed to an element.

Anywhere you can use an ID you could use a class instead. The reverse is not true.

The convention seems to be to use IDs for page elements that are on every page (like "navbar" or "menu") and classes for everything else but this is only convention and you'll find wide variance in usage.

One other difference is that for form input elements, the <label> element references a field by ID so you need to use IDs if you're going to use <label>. is an accessibility thing and you really should use it.

In years gone by IDs were also preferred because they're easily accessible in Javascript (getElementById). With the advent of jQuery and other Javascript frameworks this is pretty much a non-issue now.


j
jjclarkson

A CLASS should be used for multiple elements that you want the same styling for. An ID should be for a unique element. See this tutorial.

You should refer to the W3C standards if you want to be a strict conformist, or if you want your pages to be validated to the standards.


J
JR.

Classes are like categories. Many HTML elements can belong to a class, and an HTML element can have more than one class. Classes are used to apply general styles or styles that can be applied across multiple HTML elements.

IDs are identifiers. They're unique; no one else is allowed to have that same ID. IDs are used to apply unique styles to an HTML element.

I use IDs and classes in this fashion:

<div id="header">
  <h1>I am a header!</h1>
  <p>I am subtext for a header!</p>
</div>
<div id="content">
  <div class="section">
    <p>I am a section!</p>
  </div>
  <div class="section special">
    <p>I am a section!</p>
  </div>
  <div class="section">
    <p>I am a section!</p>
  </div>
</div>

In this example, the header and content sections can be styled via #header and #content. Each section of the content can be applied a common style through #content .section. Just for kicks, I added a "special" class for the middle section. Suppose you wanted a particular section to have a special styling. This can be achieved with the .special class, yet the section still inherits the common styles from #content .section.

When I do JavaScript or CSS development, I typically use IDs to access/manipulate a very specific HTML element, and I use classes to access/apply styles to a broad range of elements.


A
Al Lelopath

CSS is object oriented. ID says instance, class says class.


P
Peter Mortensen

When applying CSS, apply it to a class and try to avoid as much as you can to an id. The ID should only be used in JavaScript to fetch the element or for any event binding.

Classes should be used to apply CSS.

Sometimes you do have to use classes for event binding. In such cases, try to avoid classes which are being used for applying CSS and rather add new classes which doesn't have corresponding CSS. This will come to help when you need to change the CSS for any class or change the CSS class name all together for any element.


Twitter Bootstrap uses this principle - i.e. there are no IDs used at all (v3.3). It's a more extreme example because they need their library to be as generic as possible. It does show the benefit of only using classes - which is that you can then apply it across many more sites with less changes
P
Peter Mortensen

CSS selector space actually allows for conditional id style:

h1#my-id {color:red}
p#my-id {color:blue}

will render as expected. Why would you do this? Sometimes IDs are generated dynamically, etc. A further use has been to render titles differently based on a high-level ID assignment:

body#list-page #title {font-size:56px}
body#detail-page #title {font-size:24px}

Personally, I prefer longer classname selectors:

body#list-page .title-block > h1 {font-size:56px}

as I find using nested IDs to differentiate treatment to be a bit perverse. Just know that as developers in the Sass/SCSS world get their hands on this stuff, nested IDs are becoming the norm.

Finally, when it comes to selector performance and precedence, ID tends to win out. This is a whole other subject.


e
ermau

Any element can have a class or an id.

A class is used to reference a certain type of display, for example you may have a css class for a div that represents the answer to this question. As there will be many answers, multiple divs would need the same styling and you would use a class.

An id refers to only a single element, for example the related section at the right may have styling specific to it not reused elsewhere, it would use an id.

Technically you can use classes for all of it, or split them up logically. You can not, however, reuse id's for multiple elements.


A
Adam A

Class is for applying your style to a group of elements. ID styles apply to just the element with that ID (there should only be one). Usually you use classes, but if there's a one-off you can use IDs (or just stick the style straight into the element).


n
nyedidikeke

In advanced development ids we can basically use JavaScript.

For repeatable purposes, classes come handy contrary to ids which supposed to be unique.

Below is an example illustrating the expressions above:

<div id="box" class="box bg-color-red">this is a box</div>
<div id="box1" class="box bg-color-red">this is a box</div>

Now you can see in here box and box1 are two (2) different <div> elements, but we can apply the box and bg-color-red classes to both of them.

The concept is inheritance in an OOP language.


M
MERLIN THOMAS

1) div id is not reusable and should only be applied to one element of HTML while div class can be added to multiple elements.

2) An id has greater importance if both are applied to the same element and have conflicting styles, the styles of the id will be applied.

3) Style element always refer a div class by putting a . (dot) in front of their names while div id class is referred by putting a # (hash) in front of their names.

4) Example :-

class in