tags:

views:

137

answers:

4

Basically, I want to know what is best to avoid future problems and confusions with CSS code...

Naming CSS proprieties like this:

div#content 
ul#navigation
div.float-left

(Its really unnecessary to do this?)

or just

#content
#navigation
.float-left

I don't have experience with big projects so I wish someone could tell me which method is better to use while the HTML and CSS get longer.

Thanks in advance!

+7  A: 

It depends what you want to happen.

#content

will apply to everything with id="content", but

div#content

will only apply to a <div> with id="content".

This is usually more of an issue with classes since IDs should be unique across all elements on a page.

So the bottom line is, if you know the style information will only apply to HTML elements of a certain type, then include the element tag. This can stop styles from being unexpectedly applied to different elements with the same class (or ID, but that's naughty).

miknight
A: 

It's usually better to use tag#id because element selection will be quicker since it'll be working with a smaller set of possible elements.

Robert Koritnik
Wrong. Internal CSS selectors are evaluated from right to left. If you specify tag#id, the browser will *first* look for #id, and *then* check for the tag. Since the #id is already unique across all elements on the page, the second check is completely unnecessary. (Unless you want to apply the same id to different tags on different pages, which is rather unusual in practice. That's what classes are there for.)
RegDwight
Google says nope: http://code.google.com/intl/de-DE/speed/page-speed/docs/rendering.html
Boldewyn
+1  A: 

Use explicit tags when necessary, and use general selectors when necessary. One of the added benefits is the likely speed of selecting the proper element when you use the tagname. Plus this will help you while viewing the markup to know what is what:

h1.title { font-size:18px; }
h2.title { font-size:14px; }
p.title  { font-size:12px; }

In this case, it's not only helpful to me to know what the tag is, it's absolutely necessary in order to distinguish between multiple classes. As other have suggested, this is really only the case with className's, since they can be used for multiple rules, whereas ID's are supposed to be used only once per page to represent a specific element on the page.

So in reality, use the explicit tag-references when it's necessary (notice my multiple .title classes), and when you want a bit of added understanding whilst viewing your stylesheet.

Jonathan Sampson
A: 

I prefer the following:

/*IDs by themselves*/
#content{...}
#navigation{...}

/*Classes by themselves (unless the nesting is required)*/
.navoption{...}
.footerlink{...}

#specialSection.navoption{...}

This allows the greatest flexibility for re-use, while still giving you the option to "refine" a selector (or override one) for a specific scenario.

scunliffe