CSS Naming – Best Practices for Naming CSS Classes and IDs

css

I'm quite a CSS beginner. I've read some introductory books but now I came across a sort of question that isn't answered in any of them:

Let's say I have a basic HTML-based website with a standalone CSS file. Now I'm creating a new CSS class or ID and I want it to have a meaningful name of course because I'll probably come back to those lines a couple of times again. For creating a meaningful name there are two options:

  1. I can name them hide-upper-space or small-seethrough-border – these kinds of names are very helpful when reading the HTML file, but in CSS file there will be a mess of all these classes and IDs from all HTML documents mixed together. Moreover, when I want to remove or modify one HTML document I won't be able to clear or modify the appropriate lines in the CSS file because I won't know if they affect also some other HTML documents.

  2. On the contrary, I can name them blog-footnote or gallerythumbs-upper-left and it will make my CSS file thoroughly readable, structured and easily modifiable, but it's useless information in HTML documents – when you're reading the HTML code for the footnote of your blog then blog-footnote is just plain useless class name.

I hope you get my point.
I'd guess that one of these options is the actual way how the CSS should be used but I can't figure out which one and why. Thank you for helping me to use the CSS the proper and effective way.

Best Answer

I'm no HTML/CSS expert so take this answer with a grain for salt but I think you are still missing the essence of why CSS exists in the first place.

Back in the day, we only had HTML so yes, you could tell exactly what the size, color, padding...etc of every element was, but this also made HTML harder to read more difficult to modify if you ever wanted to try different layouts and/or color schemes.

CSS was introduced so that you could have a very well defined and clear separation between document structure/content(HTML) and its visual appearance(CSS). So you want elements with names like "blog-footnote" and "gallery-thumb" because in HTML those names further help define the structure and meaning of the element. You see the element and you know exactly what it's for.

Those names are "useless" in a sense that you still have no idea how (or even where) that element will appear on the screen, but HTML shouldn't give you that information. That's what CSS is for.

To better understand this separation, take a look at CSS Zen Garden. That's exactly the same HTML document (i.e. same content) but presented using different CSS styles that people have submitted.

Related Topic