IDs as selectors

You might remember from the HTML course that one page can only have one id with the same value. No two elements can have the same id, there must not be two elements with an id="main"

Other limitation of an id is that it can only have one value.

1
2
3
<p id="multiple values not allowed">
My two cents on some FE topics
</p>

You know how bootstrap has multiple classes on the same element, for example in grid you can have something like col col-md-2 col-lg-3? That is absolutely not possible with IDs! Why is that bad? Again, reusability. What if we want to separate our CSS into components, modules or some other entities? How can we reuse that styles from #btn and #btn-block and apply it to the same element? We can’t have

1
<button id="btn btn-block"> 2 cents </button>

What’s so bad about all of that? Well, you know that DRY principle aka Do not repeat yourself? If we are using id on some element and later we want to reuse styles from that id selector and apply them to some other element on the same page, we will not be able to do it. You can’t have two elements with the same id on the page, therefore styles from that id are not reusable.

1
2
3
4
5
6
7
8
9
10
11
#main {
background-color: purple;
}

<p id="main">
My two cents on some FE topics
</p>

<p id="main">
My two cents on some UI topics
</p>

Codepen

As you can see it works, but if we ran our code through the validator, we will get an error:

error

HTML will not throw an error in your face like JS, Python or Ruby. It will just suffer in silence and tolerate mistakes. Browsers became more developer and user friendly, they will still interpret your code and do their best to show your the result you wanted.

Other things I have seen is using ID as an overwriting tool. Yes, it does have precedence before the class. No doubt there.

1
2
3
4
5
6
7
#main {
background-color: purple;
}

.main {
background-color: orange;
}

Id will overwrite class even though class come after the id in the code. It has precedence. But again, reusability! What if you want to overwrite those styles in ID? You will have to fight that ID with some other selector. What if you later want to overwrite that? Uf, it goes on and on.

The other thing about IDs is that they are reserved for targeting elements with JS. Developers like to keep their code separated, they like to make their code more readable, more understandable to other humans. For computer aka browser, it doesn’t matter where are we going to put our code. We could chunk all of our code in one HTML file, HTML&JS&CSS all together and it would still work in the browser, right? But we humans like to see things structured and organised, that is why devs split their code, we separate HTML from CSS, CSS from JS and HTML from JS. We don’t want to do two different things in ID: one with JS, other with CSS. That is why we use class for CSS and ID for JS.

My two cents are not to use classes instead of IDs