Steve Bennett
Steve Bennett

Reputation: 126225

How to manage combinations of styles: multiple classes, specific classes, or context?

I'm not much of a web designer or programmer, but I seem to run into this issue with CSS classes: what's the best way of managing sets of CSS classes that share attributes in common?

For example, I'm currently working on an application with a status bar representing the status of a file transfer. It's used in three different locations, each of which is a different size. In addition, if the transfer fails, the bar should be a different color.

What's the best approach, in general:

  1. Add "statusbar" and "transfer-failed" classes to the divs independently, and check for their combined existence?
  2. Have "statusbar" and "statusbar-failed" classes, set the class appropriately, and use careful CSS structuring to avoid repeating code.
  3. Have a "statusbar" class, then use context like the div being inside a "summary" table or a "transfer-failed" div to further specialise it.

Are there any general rules? Approach 3 seems fragile, because changing the name of a seemingly unrelated class could break stuff. Approach 1 feels strange somehow, having classes like "failed" that would be meaningless without another class, and could also mean different things in different contexts (eg, "failed" could also be applied to a failed form validation...) Approach 2 sometimes gets unwieldy, with lots of very specific classes with long names.

Upvotes: 0

Views: 236

Answers (2)

Ayman Safadi
Ayman Safadi

Reputation: 11552

  1. If there will always be only one "status bar" feel free to use an id instead of a class for it.

  2. If there will be multiple on the same page, and they look anything alike, stick with class.

  3. Assign a transfer-failed class when appropriate. In in your CSS, under this class, should only have the properties that differentiates it of the default "status bar". Personally, I like #3 (the context approach). WordPress and other CSMs assign the page name and category (and anything else you'd like) as <body> classes. Modernizr uses the <html> tag. More info here: http://perishablepress.com/dynamic-body-class-id-php-wordpress/

  4. @Lokase's SMACSS is great. For more tips on organizing your CSS, check this out: http://coding.smashingmagazine.com/2007/05/10/70-expert-ideas-for-better-css-coding/

Upvotes: 1

Lowkase
Lowkase

Reputation: 5699

Take some time to look at a few CSS methodologies or frameworks, I am a fan of SMACSS

There are a lot examples of best practices out there, you just have to find them and go through the learning curve.

Upvotes: 0

Related Questions