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?


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.


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.


How about using header tags

#title h1{/* CSS */}

<div id="header">
    <h1>Title</h1>
</div>

I guess that's what the tags are there for :)

链接地址: http://www.djcxy.com/p/10004.html

上一篇: 在Node.js中,是否可以告诉观察文件被移动到哪里?

下一篇: 类与嵌套CSS的ID