2
<div id="stockexchange-id" class="stockexchange-class">Text</div>

In the example above I added both a class and an id into the div statement. Is there a difference between them? If I call .stockexchange-class CSS instead of #stockexchange-id CSS does it make any difference? If it doesn't then what it the point of having both of them? Also which one would be better to use?

matthew
  • 123
  • 1
  • 1
  • 6
  • It could matter for cascading reasons, but this question is off-topic here – s_ha_dum Nov 09 '15 at 02:39
  • It's just an attribute of your div element. Standard of using ID is specific only one element but the class can referenced many element. Using class would be better to apply with many element selector. – ZenithS Nov 09 '15 at 02:49

2 Answers2

3

The biggest difference is that a document can have multiple elements with the same class, but not with the same ID. An Identifier must be specific to a certain element within a document (i.e. full HTML page).

When applying CSS styling, some experts have recommended using classes over IDs to avoid specificity wars. CSS Lint (http://csslint.net/) recommends this.

The reason is that stylesheets are read from top to bottom, but IDs take precedence over class. This means that:

#stockexchange-id { 
  color: blue;
}

.stockexchange-class {
  color: red;
}

Would color the text blue, even though red comes later. Here's a good graphic explaining specificity: https://stuffandnonsense.co.uk/archives/images/specificitywars-05v2.jpg.

If everything has the same specificity, and most styles are applied via a single class, it makes the CSS easier to reason about, since it will read from top to bottom without extra styles being mixed in different orders. It also makes it easier to override classes, which can be useful.

Finally, if you style based on classes, you can re-use the styling on the same page by applying the class to another element on the page. With IDs, since they are unique, you cannot do this. Even if you think an element is unique on a page (e.g. a Buy Button), this may not always be the case. A designer may request the same element again later in the page.

Hans
  • 968
  • 7
  • 16
0

You can only use an ID name once in any XHTML or HTML document. Duplicate ID tags will cause your page to fail validation, and can have negative effects when using JavaScript with them. Simply put, an ID is like the sticker that says "you are here" on a mall directory, and there can only ever be one of those.

Classes, like ID's, can also be used to in JavaScript scripts, but unlike ID's, they can be used multiple times in the same HTML document. This separation of content from presentation is what makes sites powered by CSS more robust, but some don't know the full extent to which they can use classes.