wyc
wyc

Reputation: 55273

Mentioning the HTML TAG element before a CLASS or ID (Good or unnecessary CSS practice?)

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

(It's 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.

Upvotes: 2

Views: 1157

Answers (3)

scunliffe
scunliffe

Reputation: 63588

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.

Upvotes: 0

Sampson
Sampson

Reputation: 268344

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.

Upvotes: 2

miknight
miknight

Reputation: 493

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).

Upvotes: 8

Related Questions