CSS – What to Use Instead of IDs in Selectors

coding-standardscoding-stylecsshtml

I recently installed a csslint package for my Atom text editor. I keep getting warnings saying "Don't use IDs in selectors." I found this weird since I've always been using IDs in selectors in CSS, and I haven't really run into any coding or syntactic problems using them.

On StackOverflow, I found posts, like this one, stating that I shouldn't use IDs because they have priority over classes. However, I found another post that states I should use IDs because they have priority over classes. I understand both of these posts, but I still don't know if I should continue to use them or not.

Lets say I have this code as an example:

HTML

<div id="opening-subject-container">
    <div class="subject"></div>
    <div class="subject"></div>
    <div class="subject"></div>
</div>
<div id="body-subject-container">
    <div class="subject"></div>
    <div class="subject"></div>
    <div class="subject"></div>
</div>

CSS

.subject {
    width: 100%;
    height: 20px;
}
#opening-subject-container .subject {
    background-color: red;
}
#body-subject-container .subject {
    background-color: blue;
}

where I want the first subjects in the opening container to be red and the remaining subjects in the body container to be blue.

If I shouldn't ever use IDs in CSS selectors, what should I use instead?


Thanks for everyone's advice. I decided to stick with using IDs since they are convenient and I am able to keep track of when I should use an ID and when not to. I got tired of the warning messages in the lint, so I just changed the source code and deleted some rules that display warnings like this.

Best Answer

ID's are needed to be unique while classes tend to group several elements' style together. I read somewhere it as this analogy :

<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.

Moreover , ID elements tend to have higher priority over other selectors which makes it harder to reapply rules on them. There was an stackoverflow answer regarding some JS function selecting only first occurence of same ID elements too (I'll include link asap).

EDIT : try getting a bunch of elements by using getElementByID() in js and you'll notice what I was trying to say.

On the other hand , IMO you shouldn't take csslint complaints too strictly on your css rules. Some of them are flawed by nature.

reference

Related Topic