Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class vs ID with nested CSS

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 style title only once, I would like to use an id. But then the name would have to be something like header_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?

like image 715
lucas clemente Avatar asked Nov 16 '11 00:11

lucas clemente


2 Answers

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.

like image 67
unrelativity Avatar answered Sep 29 '22 20:09

unrelativity


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.

like image 36
Joseph Marikle Avatar answered Sep 29 '22 20:09

Joseph Marikle