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:
- Add “statusbar” and “transfer-failed” classes to the divs independently, and check for their combined existence?
- Have “statusbar” and “statusbar-failed” classes, set the class appropriately, and use careful CSS structuring to avoid repeating code.
- 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.
If there will always be only one “status bar” feel free to use an
idinstead of aclassfor it.If there will be multiple on the same page, and they look
anything alike, stick with
class.Assign a
transfer-failedclass 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/@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/