Recently I’ve been learning CSS. And I must say, I find it challenging. One of the things that I’ve been wondering lately is when I should use a CSS class vs. an ID. After a bit of research, I've learned some things and I’ll share them here.
For those of you who aren’t very clued into what CSS is and does, I’ll give you an brief overview. Websites are made of HTML - that stands for hypertext markup language (actually not important, just fun to say) - and CSS - cascading style sheets (also not important and a little bit less fun to say).
HTML is the bones and structure of the content on the page. You can think of it as the layout of a house. It’s the floor plan. For example, check out the image below.
Here I can see that the html (floor plan) is showing that the page will have a header, a paragraph of text, and an image. It’s creating the structure of our house and what will be inside it.
CSS on the other hand is all of the styling of the site. You can think of CSS as the interior decorating of the house (albeit really really frustrating interior decorating… like interior decorating with your eyes closed. At least that is how it feels for me right now).
Within CSS there are the concepts of classes and IDs. You can use classes and IDs as an identifier for styling. It’s a way to isolate an item in a specific area of the site to apply styling. A few key things though about the differences between the two:
ClassesFun fact: the browser uses IDs to know where to locate a element on a page. If you were to know the element’s ID on a page, you could add that value to the end of a URL and the browser will scroll to that part of the page with that element.
So that’s all well and good. I get the difference so far. But while I was coding, it still wasn’t entirely clear to me why I should use a class name over the ID (and vice versa) when applying my CSS styling.
In my research, two things have become apparent in deciding to use one over the other:
In relation to number 2, I could probably write a much much longer essay about how the CSS cascade works, but I'd rather defer to Mozilla web docs. There's great documentation on how the cascade works and the algorithm applies styling. You can check it out here. I'm looking foward to jumping into JS next week and learning more about how IDs play a role in hooking into elements. Stay tuned to see what I learn!