Reputation: 6389
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?
Upvotes: 7
Views: 17690
Reputation: 3720
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.
Upvotes: 3
Reputation: 43
Seems like you're more worried about naming convention.
It's totally okay to just use
#header #title {/** css **/}
In your case the best method is probably to use the "dirty" method.
I'm not sure why you would choose to use span over h1, h2 because I would just do
#header h1 {/** css **/}
since you most likely will only have one h1 tag within your #header
Upvotes: 0
Reputation: 85046
Use an ID if there is only one element you want to style since IDs cannot be duplicated. If there is a possibility that there could be multiple elements with the class title
(both in and outside of the #header
div), then stick with your first CSS example as this will ensure that only elements with the title class that are inside of the #header element will be styled.
It really depends on what the rest of your HTML looks like and what you are trying to style.
Upvotes: 0
Reputation: 78520
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.
Upvotes: 2
Reputation: 736
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 :)
Upvotes: 0