Class vs ID with nested CSS
Solution 1
It actually doesn't really matter.
What matters about your markup is that it's readable; HTML is about being semantic, so that your markup represents your content. By doing so, if you come back to your HTML a few months later without touching it, you should be able to quickly pick up on what on earth you wrote :)
Semantically, #header .title
makes a lot more sense to me over #header #header_title
, for two reasons; one, since it's easier to read, and two, since the purpose of ids is, well, to identify! You could use #header_title
by itself, but it's much cleaner to limit the amount of ids you have.
Solution 2
Using #id .class {style:rules;}
is not "dirty". It is the correct way of doing it. Also, if you "might have other titles in the HTML", it would be even more correct to use classes rather than have 15 id based rules.
lucas clemente
Updated on June 05, 2022Comments
-
lucas clemente about 2 years
Suppose a HTML like this:
<div id="header"> <span class="title">Title</span> <!-- more spans and other things here --> </div>
This would work together with a nested CSS:
#header .title { /* CSS */ }
This works of course, but I don't like the usage of
class
here. As I need the styletitle
only once, I would like to use an id. But then the name would have to be something likeheader_title
(since I might have other titles in the HTML), resulting in a CSS#header #header_title { /* CSS */ }
Now this seems to defeat the purpose of nested CSS, then I could just drop the first
#header
completely.I can't really figure out a way to do this "right". Am I missing something, or do I just have to live with some "dirty" code here?
-
lucas clemente over 12 yearsSee my comment above. It's actually not a single span in there, but many, including other elements. I just stripped it down for simplicity, maybe I went a bit too far ;)
-
Mike Cao over 12 yearsDid you mean to type #header instead of #title?
-
lucas clemente over 12 yearsI need the class
title
only once, but have different "titles" that are styled differently. -
rmorse over 12 years@lucasclemente I wouldn't include the name of the parent itself, to keep it readable it is unnecessary, I guess if its an ID you want to use (because it will only be used once) I would use a prefix to keep it simpler? #header #hTitle ?