Save Time By Using Multiple Classes

Evening Tip: Save Time By Using Multiple Classes.

Aug 13th in HTML & CSS by Robbie White

One of the most exhausting aspects of web development is writing out endless amounts of CSS styling for various elements - that differ only slightly in style from one another. It has taken the life (or will) of many a talented designer. Well, why give each element its own unique CSS entry, when you can mix match and add re-usable CSS styling to elements using multiple CSS classes?

PG

Author: Robbie White

This is a NETTUTS contributor who has published 1 tutorial(s) so far here. Their bio is coming soon!

Step 1: Set Up The CSS

Lets start with identifying and writing out some of our most common CSS markup. We'll set them up as individual styles. The ones that we've set up here are the most basic, but the same technique can be applied to even the coolest CSS 3 properties.

.primaryColor{
color: blue;
}

.articleImage
{
border: 1px solid #292929;
padding: 5px;
}

.standOut{
font-size: 22px;
}

.important{
font-weight: bold;
}

.floatRight
{
float: right;
}

Step 2: Applying The Classes In Our Document

  • <p class="primaryColor important">This text will be blue and bold</p>
  • <img src="#" class="articleImage floatRight">This image will be floated to the right, and will have some padding and a border.</p>
  • <p class="standOut">This text will be huge</p>
  • <p class="primaryColor standOut important">This text will be blue, 22px large, and bold. </p>

Why It's Useful

This can be a massive help, especially when designing layouts... you can use one class to define the size and width, and another class to define the positioning. Hope this helped!

Editor's Note: Keep in mind that, in some of the older browsers - meaning older than IE 6 - this "multiple classes" method will fail. What are your thoughts on this approach? P.S. Have a killer quick tip? Email us and we'll talk.


Related Posts

Check out some more great tutorials and articles that you might like

Enjoy this Post?

Your vote will help us grow this site and provide even more awesomeness

Plus Members

Source Files, Bonus Tutorials and
More for $9 a month for all TUTS+
sites in one subscription.

Join Now

User Comments

( ADD YOURS )
  1. PG

    Clayton Ferris August 13th

    Applying multiple classes is a great practice, however that is a terrible example. Class names should be representative of your content not the style of your content. What happens when you redesign your site in a few months, or just decide to change color schemes? Your .blue class is totally useless.

    ( Reply )
  2. PG

    Roc August 13th

    Yay First :D

    ( Reply )
  3. PG

    John August 13th

    Good Tip, I rarely use classes to the extent I should

    ( Reply )
  4. PG

    Jeffrey Way August 13th

    @Clayton - Absolutely. Very good point. It may not seem like a big issue at first - but you’ll definitely have some problems down the line.

    ( Reply )
  5. PG

    James August 13th

    A nicely written little tip, thanks! :)

    This does raise the question of whether it’s okay to sacrifice semantics for convenience. Giving an element a single and meaningful class/ID and applying all styles to that is a much more semantic approach. However, there is the risk of bloated and unnecessary code with the semantic approach plus it would probably be less maintainable than using multiple classes as you’re suggesting. But then using multiple classes may have the same bloated result because of all the classes you’d have to add to each element. And then it would also be hard to maintain! - For example, if you wanted to change the size of all your “size22″ (i.e. class=”size22″) elements you’d have to go through every element and rename the class correspondingly!!

    So, I suppose the whole thing is still up for discussion. Anyone who reads this should consider this though - Is it better to name a class according to it’s purpose (e.g. class=”warning”) or according to it’s style attributes (e.g. class=”red”)?

    Plus there is the whole issue of backward compatibility / cross-browser support!

    ( Reply )
  6. PG

    Jeffrey Way August 13th

    @James - Yeah - people split on this concept. I tend to stick more with naming according to its “purpose”. Although, I’ve definitely done both. Cross-browser support is fairly widespread…except for very, very old browsers.

    ( Reply )
  7. PG

    Stan Grabowski August 13th

    Good advice. One quick question though. Why would you use a class name with a color or some other visual term? If your client or boss comes back and asks you to change things from blue to orange, you then have to change your class names AND your CSS file.

    Class names (and IDs) should relate to what they are marking up, not to how it will look. Something like is an example of how classes should be named.

    ( Reply )
  8. PG

    Chris Coyier August 13th

    I agree that the theory here is good but the actual example is problematic. You’ll make thing easier on yourself and the lifespan of your site if you avoid names like “blue” and “bold” and make them describe what you are trying to accomplish instead like “callout” or “button”.

    ( Reply )
  9. PG

    Jonathan August 13th

    What are your thoughts on this approach?

    I know longer design for anything older than IE 6. If car companies no longer support their vehicles after 10years ( VW ) why must we support outdated browsers. Besides, the number of users of IE 5 and below are in the single digit %. So why bother.

    I have been playing with classes as of late, at it really opens up doors of possibilities. For example - created a function the outputs a post class( post1 Y2008 M08 D15 protected authorname category-xyz etc)
    Now if I want assign a color to different authors, no problem, or year, or month.

    NBThing to remember here is that the styles (classes) are applied in a cascading manner, so you have to be careful in duplicating the styles. For example, if you set the width for CSS class XY, it will override the one set in the class YZ.

    ( Reply )
  10. PG

    sas171 August 13th

    Yeah, style=”width: 100px; float: right;” is even shorter, isn’t it? You don’t have to define all the silly classes in the extern CSS file!

    Seriously, we use CSS to get one abstraction layer more and distinguish between content (XHTML) and presentation (CSS). Using your advice people will bring the presentation layer information back into content layer.

    The CSS classes should reflect the logical nature of the element. E.g.: hint, comment, category-name, post-excerpt. However the last one could be written as … … … . In this case you are able to change the look of the elements when required without touching the XHTML and your XHTML will be much cleaner.

    Cheers.

    ( Reply )
  11. PG

    Ryan Imel August 13th

    I second everyone’s remarks about this being an excellent tip but a poor example. We shouldn’t be instructing people to add classes based on the visual outcome under any circumstances.

    Also, for anyone who uses WordPress that likes the idea of elements being packed with semantic classy goodness, check out Sandbox, a theme for those who build themes. Trust me, it’s overflowing with developer happiness: http://www.plaintxt.org/themes/sandbox/

    ( Reply )
  12. PG

    shofr August 13th

    I agree with Clayton. Anyone that sent me CSS marked up like this wouldn’t get much respect from me. This method is short sighted and borders on counter intuitive.

    ( Reply )
  13. PG

    Jeffrey Way August 13th

    Everyone - It was my initial intention to leave the class names relating to the style in - out of courtesy to the author. Plus, I thought it would make for an interesting debate. However, considering the fact that many new developers will be learning from this, I’ve edited the names to something that I’m more comfortable with.

    Although “.center” refers to the styling, I think this is okay…But that can definitely be debated. I suppose it all comes down to how semantic you want to be!

    Keep the comments coming. This is an important subject.

    ( Reply )
  14. PG

    James August 13th

    Yeh, good idea Jeffrey. Like you said, a lot of people use this as a learning resource - we don’t want them getting the wrong idea…

    ( Reply )
  15. PG

    Jonathan August 13th

    I second James. Good Idea Jeffrey, as for center I use ac = align center ; al = align right ; ar = align left ; fr = float right ; fl = float left and one more fix = more in depth clear:both

    Not the best way, but works for me.

    ( Reply )
  16. PG

    m0nkie August 13th

    my example:
    imagine, i need unordered list of items with bullets coloured differently for each item. my bullet will be 6 by pixels image. i’ll have 5 items. so i create image 6 by 30 pixels containing blue, orange, gray, green and pink bullet. then for the 1st bullet i assign background-image, and then for others i change its position using my classes..

    html:

    list item #1
    list item #2
    list item #3
    list item #4
    list item #5

    css:

    li .dot {
    position : absolute;
    top : 0.4em;
    z-index : 1;
    width : 6px;
    height : 6px;
    margin-left : -15px;
    background : url(fo-list.png) no-repeat;
    }

    .orange {
    background-position : 0 -6px;
    }

    .gray {
    background-position : 0 -12px;
    }
    .green {
    background-position : 0 -18px;
    }
    .pink {
    background-position : 0 -24px;
    }

    ( Reply )
  17. PG

    m0nkie August 13th

    oops…
    here is disappeared html:

    ( Reply )
  18. PG

    Taylor Satula August 13th

    Ive been deving a css file that does rbg align font etc. so this will be helpful

    ( Reply )
  19. PG

    Melvin Nieves August 13th

    Love the css tips, thanks!

    ( Reply )
  20. PG

    Ben Griffiths August 13th

    Personally I have never been a fan of doubling up classes on a single element - the risk is to high for me to brake something without realizing it when modifying one of the classes. I prefer instead to create a new single class to handle the difference, eg:

    .image {
    border: 1px solid #000;
    }

    .image-right {
    border: 1px solid #000;
    float: right;
    }

    For me this gives much more control. It may make the CSS larger, and slightly more complicated, but safety of editing rules over this for me.

    ( Reply )
  21. PG

    Medium August 13th

    Nice tip, keep them comming :)

    ( Reply )
  22. PG

    Dan August 13th

    Good idea naming them .primaryColor .secondaryColor instead of what I see people doing (e.g. .blueColor etc…). My advice is to make sure you really need multiple classes for what you’re doing before you actually use more than one. Keeping layout and style as separate as possible is key when it comes to easily maintaining websites.

    ah woops, you have a typo posted as of 8/13 3:34pm:

    .floatRight {
    float: rightright;
    }

    nice post idea! keep them coming!

    ( Reply )
  23. PG

    Philo August 13th

    Great Tip! :)

    ( Reply )
  24. PG

    Craigsnedeker August 13th

    Awesome tip, I never knew you could do that!

    ( Reply )
  25. PG

    Dan August 13th

    These tips are getting some traffic eh, nice, keep em coming

    ( Reply )
  26. PG

    Dave Tufts August 13th

    Taking what Dan said even farther, it’s important the CSS definitions don’t describe how something looks right now, but rather what it is.

    “floatRight” describes how it looks. The whole purpose of an external CSS is that you can deal with layout issues separately. With .floatRight, if your layout changes and you want the image on the left, you have to change the CSS and the HTML. Instead, what is the image? Describe the content:

    img.headshot { float: right; }
    img.primary {float: right; }

    Also, to comment on what Ben said, you should never need .image { } or .image-right { }. Instead don’t use any class:

    .article image {
    border: 1px solid #000;
    }
    .article image.primary {
    border: 1px solid #000;
    float: right;
    }

    ( Reply )
  27. PG

    insic August 13th

    i started to like this quick tips. keep it up nettuts!

    ( Reply )
  28. PG

    Shane August 14th

    Well - this article has certainly provoked a lot of debate, which is a good thing.

    There are different levels of semantics with CSS - I’d never use .blue, for example, because, as many people have said, your .blue class might not have blue characteristics further down the line.

    I prefer to use semantic terms such as header, footer and sidebar. But… I have mixed things up a little by using multiple classes.

    In his book ‘Transcending CSS’, Andy Clarke suggests that for layout, sites use a similar convention, such as header, footer and so on. That way, the layout ‘blocks’ are consistent across sites, and a user-defined stylesheet could style them in a similar way.

    ( Reply )
  29. PG

    Jason August 14th

    I agree with Clayton, to a point. although the class can be described according to its content this does not mean it has to. The content can change, but the element that contains it should stay the same. But in saying that, thats the whole beauty of CSS. Giving the user to be ability to tag into the script and name sections as they see fit. Ok semantics can and probably does play a big part in all this, but it is not required, and at the end of the day this tut is only an example of the functionality that a class has. To be able to use a single css rule over and over on a page.

    Not the best Tut, but the thought behind it is correct.

    ( Reply )
  30. PG

    Manuel August 14th

    I always used a floatRight-class but never thought about a primaryColor-class or an important-class. Nice idea!

    ( Reply )
  31. PG

    Kim Dolleris August 14th

    What Insic said :)

    ( Reply )
  32. PG

    ben August 14th

    very nice trick,thanks

    ( Reply )
  33. PG

    Rob August 14th

    I don’t know why everyone is ganging up on you for your CSS class names. The benefit between generic titles designed to convey the overall effect, versus something more specific is pretty negligible. On the one hand, if your name expressly defines what the class is to do… it makes it a hell of a lot easier to see what’s going on in your code. On the other hand, generic names that convey a more vague approach offer you the flexibility of altering the specifics (ie. blue to yellow, 21pt to 25pt, etc) without muddying up the waters with a class name that suggests something radically different.

    But then… look at .standOut. If you saw <div class=”standOut”> you wouldn’t know immediately if that class had a bolding effect, increased the font size, doubled the margins, italicized it… etc. ’standOut” could encompass any of all of those, making the choice between generic and explicit largely a matter of taste in my opinion.

    Regarding the tip though; I think it’s absolutely brilliant. I remember when I first learned you could specify multiple styles I went looking through other sites code and wondering ‘why the hell aren’t people USING this’. I find it’s great for when I have two blocks with many of the same styling, but then one or two things that are different (like maybe ‘A’ has green text and ‘B’ has blue).

    As for browsers lower than IE6… no worries. If you’re still coding for browsers lower than IE6 well, kudos to you and all… but I would ask why. If your client cannot function without that 0.3% market then most likely he needs to upgrade his OWN system.

    ( Reply )
  34. PG

    fricks August 14th

    Good tip!
    Thank you :)

    ( Reply )
  35. PG

    Brian August 14th

    Isn’t it best ot keep the markup XHTML elements such as etc as class free as possible and target all of it from the CSS file so changes in future can be done from the CSS file and the markup does not need to be touched.

    ( Reply )
  36. PG

    Jason August 14th

    @Rob, the stand out class doesn’t need to convey that it deals with bolding. The idea behind this class is, if you decide you want to change the way your elements can stand out you can do it once in the css without having to change it a hundred times in the CSS.

    For example: Client brief says first paragraph must stand out. You present them with the results of this css.

    .standOut {
    font-size: 22pt;
    font-weight: bold;
    }

    When you present the complete beta site to the client, client asks if something else could be done to make it stand out more. You respond with:

    .standOut {
    font-size: 22pt;
    font-weight: bold;
    background-color: #999999;
    border: 1px solid #666666;
    }

    If you had been using a class name like ‘.bold22′ you’d be in for a fun few hours of find and replace.

    The idea is to make it so the function is clear not the style.

    ( Reply )
  37. PG

    Dino August 14th

    I think there’s a typo sir:

    .floatRight
    {
    float: rightright; <– wrong, wrong…
    }

    ( Reply )
  38. PG

    Braden Keith August 14th

    very quick and useful, thank you. I don’t usually think of adding multiple classes to an object like that

    ( Reply )
  39. PG

    Wayne August 15th

    @Ben — Yes, that’s the approach I take. There may be some redundancy, but it allows me to keep things straight, and I worry less when I need to tweak a class.

    ( Reply )
  40. PG

    Ann August 15th

    I am super lazy about making classes, but I always spending more time adding style to individual paragraphs. I really need to start doing this more often.

    ( Reply )
  41. PG

    Cameron August 15th

    This is a great tip. I’ll be sure to use it.

    Thanks!

    ( Reply )
  42. PG

    Lamin Barrow August 16th

    You code markup wont be valid XHTMl if you go down the path of using multiple classes on an element.

    ( Reply )
  43. PG

    Jammin August 18th

    Good tips but word up to Dave Tufts tip!

    ( Reply )
  44. PG

    James Tryon August 19th

    This is one of those things that you know about but you never practice. Meaning its a great tip but you just dont think about it when you could be using it.

    Thanks for the wake up, also i got what you where saying. there is no need to pick it apart that much.
    Thanks for you help.

    ( Reply )
  45. PG

    harem August 29th

    hi Insic!

    ( Reply )
  46. PG

    Jonathan September 1st

    This article leaves something to be desired, but it’s a great idea.

    You’re using named elements, rather and descriptive elements.

    What css is trying to emulate is something called a polymorphic function, or polymorphism. Code should be written without a specific type, so that you can re-use that code down the road on all kinds of things you may not have originally intended. So, for example, instead of calling your image callouts .articleImage, consider something like .decoratorstyle1. There are a ton of naming conventions, and that’s NOT THE POINT of this. If you use abstraction, you can re-use your base classes outside of their intended name space and object space, and dramatically reduce the amount of css required, especially on complex or multi-layout sites. Remember, a subclass should only have to capture the delta of the change from the parent class, which really eliminates a lot of code.

    See this article on the subject:
    http://www.simplebits.com/notebook/2003/04/15/css_inheritance.html

    ( Reply )
  47. PG

    Jatin Meshiya September 1st

    I am Yahoo Store Developer, and I always use the CSS classes that repeat again and again. in fact if you have ever find e-Commerce layout has category page, product listing pages, home page with future products and many more… such as new arrivals in left navigation, highest rated product in right navigation etc has same block layout. In these cases we are using the same style. My mean to say one same class.

    We also maintain hierarchy in CSS. It is really very good practice in e-Commerce layout. One more thing I want to tell you that if possible then use the name that indicate the proper place that they will be apply.

    ( Reply )
  48. PG

    Dave Ellis September 5th

    This is really useful and something that I need to work on implementing more into my sites. I think a lot of being able to write your css out like this comes down to planning.

    ( Reply )
  49. PG

    srawetek September 29th

    very,very goodtip.

    ( Reply )
  50. PG

    sean steezy February 9th

    I tried doing it this way for a website once… it was a nightmare. My inheritance sucked and I had multiple style overwriting eachother… I need to get schooled on hierarchy and inheritance.

    ( Reply )
  51. PG

    Ethan February 16th

    I’m strange in the way I switch classes and ida.

    ( Reply )
  52. PG

    Greg February 28th

    @Dino - its not actually a typo but a bug in the presentation widget used to present the code sample. i’ve seen this before on other blog articles.

    ( Reply )
  53. PG

    Susan Litton May 15th

    I found this tip to be very helpful. I understand the ideas behind the notion that classes should be named to reflect content instead of styles. However, I’m working on a very large site and I keep forgetting the hex codes of my primary and secondary colors. I write them on scraps of paper on my desk but I can never find them when I need them. Creating .primaryColor and .secondaryColor classes could be helpful.

    ( Reply )
  54. PG

    Alex June 23rd

    All this complaining about descriptive named classes, did the code examples change since this article was published?

    Seems like..

    .primaryColor{

    }

    .articleImage{

    }

    define structure/are named in a way that makes them reusable.

    ( Reply )
  1. Arrow
    Gravatar

    Your Name
    June 23rd