Id vs. class in a div tag

I’m just getting started with CSS. From what I’ve seen, it makes more sense to use a class in a div tag instead of an id. Is this correct?

<div class=“container”>

<div id=“container”>

Generally speaking, a class is probably better, as it is reusable, and is not so hard to override. These days I tend to save IDs for JS hooks and on-page links.

When you say reusable, you mean multiple times on a page, right? Can you give an example of a time you would want to over-ride an id ?

Thanks.

Actually, it’s like a wrench and a hammer. You should use the right tool for the right job.

IDs:

  • Should be unique to each HTML document. That is if you are going to apply the same rules over and over… and ID is not what you want.
  • Really help when targeting javascript. Although there are many ways to target elements js, getElementByID() the simplest, so using an ID to not only add CSS but in anticipation of js is handy technique
  • Form elements. Adding an ID to a form element links it to the LABEL tag when the “for” attribute is used.
  • Semantics. As I said before, IDs SHOULD be unique some times it’s away of saying this is an ONLY element. Meocre example… but the only thing that comes to min quickly: <div id=“page”> for the outer most wrapper.
  • SPECIFITY. ID give more specificity to a rule. This is hard to understand if you dont understand specificity… but here is an example.

#anID .rule3 { color: red}
.rule1 .rule2 .rule3{color:green}

<div id=“anID”>
<div class="rule1>
<p class=“rule2”><span class=“rule3”>text</span></p>
</div></div>

The text will be red. Even tho " .rule1 .rule2 .rule3{color:green}" has more classes list and seem more innermost in the markup… throwing just ONE ID makes the other rule more specific than using several , or more classes.

That being said classes are used for the opposite reasons:

  • they can be used one or MANY times in an HTML document, and thus semantically imply an object that could occur repeatedly in the code
  • They are less specific
  • Until ‘recently’, they did not help to target elements for js
  • They have less specificity than IDs

Hope that helps to clear up things

BTW
To override an ID you either need to write it over in the code:

#MyId tag{a rule…}
#MyId tag{the same rule, different value}

this just seems kinda dumb many times.
OR you need TWO IDs ( see how using IDs willy nilly can become a mess?

#MyId tag{a rule…}
#anotherID #MyID tag{the same rule, different value}